-- Receipt compatibility for all historical QuoteJudge schemas. Additive only.
CREATE TABLE IF NOT EXISTS quote_judge_receipts (
    id BIGSERIAL PRIMARY KEY,
    receipt_id TEXT,
    tenant_key TEXT NOT NULL,
    comparison_id TEXT,
    skill_name TEXT,
    tool_name TEXT,
    status TEXT,
    input_hash TEXT,
    result_hash TEXT,
    receipt_json JSONB,
    payload JSONB,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

ALTER TABLE quote_judge_receipts ADD COLUMN IF NOT EXISTS receipt_id TEXT;
ALTER TABLE quote_judge_receipts ADD COLUMN IF NOT EXISTS skill_name TEXT;
ALTER TABLE quote_judge_receipts ADD COLUMN IF NOT EXISTS tool_name TEXT;
ALTER TABLE quote_judge_receipts ADD COLUMN IF NOT EXISTS status TEXT;
ALTER TABLE quote_judge_receipts ADD COLUMN IF NOT EXISTS input_hash TEXT;
ALTER TABLE quote_judge_receipts ADD COLUMN IF NOT EXISTS result_hash TEXT;
ALTER TABLE quote_judge_receipts ADD COLUMN IF NOT EXISTS receipt_json JSONB;
ALTER TABLE quote_judge_receipts ADD COLUMN IF NOT EXISTS payload JSONB;

UPDATE quote_judge_receipts
SET tool_name = COALESCE(tool_name, skill_name),
    skill_name = COALESCE(skill_name, tool_name),
    payload = COALESCE(payload, receipt_json),
    receipt_json = COALESCE(receipt_json, payload)
WHERE tool_name IS NULL OR skill_name IS NULL OR payload IS NULL OR receipt_json IS NULL;

CREATE INDEX IF NOT EXISTS quote_judge_receipts_tenant_idx
    ON quote_judge_receipts (tenant_key, created_at DESC);
