-- Current QuoteJudge Studio contract. Additive only: supports fresh installs and
-- databases that previously applied older QuoteJudge migrations.
ALTER TABLE quote_comparisons
    ADD COLUMN IF NOT EXISTS recommendation_vendor TEXT,
    ADD COLUMN IF NOT EXISTS result JSONB;

UPDATE quote_comparisons
SET recommendation_vendor = COALESCE(recommendation_vendor, recommended_vendor),
    result = COALESCE(result, payload)
WHERE recommendation_vendor IS NULL OR result IS NULL;

CREATE TABLE IF NOT EXISTS quote_judge_receipts (
    receipt_id TEXT PRIMARY KEY,
    tenant_key TEXT NOT NULL,
    comparison_id TEXT NOT NULL,
    tool_name TEXT NOT NULL,
    status TEXT NOT NULL,
    input_hash TEXT NOT NULL,
    payload JSONB NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

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