-- QuoteJudge Studio v1 current product contract. Additive/idempotent for existing managed databases.
CREATE TABLE IF NOT EXISTS quote_judge_comparisons (
    id BIGSERIAL PRIMARY KEY,
    tenant_key TEXT NOT NULL,
    comparison_id TEXT NOT NULL,
    input_json JSONB NOT NULL DEFAULT '{}'::jsonb,
    result_json JSONB NOT NULL DEFAULT '{}'::jsonb,
    recommendation_vendor TEXT,
    latest_receipt_id TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (tenant_key, comparison_id)
);

ALTER TABLE quote_judge_comparisons ADD COLUMN IF NOT EXISTS input_json JSONB NOT NULL DEFAULT '{}'::jsonb;
ALTER TABLE quote_judge_comparisons ADD COLUMN IF NOT EXISTS result_json JSONB NOT NULL DEFAULT '{}'::jsonb;
ALTER TABLE quote_judge_comparisons ADD COLUMN IF NOT EXISTS recommendation_vendor TEXT;
ALTER TABLE quote_judge_comparisons ADD COLUMN IF NOT EXISTS latest_receipt_id TEXT;
ALTER TABLE quote_judge_comparisons ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
ALTER TABLE quote_judge_comparisons ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW();

CREATE UNIQUE INDEX IF NOT EXISTS quote_judge_comparisons_tenant_comparison_uidx
    ON quote_judge_comparisons (tenant_key, comparison_id);

CREATE INDEX IF NOT EXISTS quote_judge_comparisons_tenant_updated_idx
    ON quote_judge_comparisons (tenant_key, updated_at DESC);

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 tenant_key TEXT;
ALTER TABLE quote_judge_receipts ADD COLUMN IF NOT EXISTS comparison_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;
ALTER TABLE quote_judge_receipts ADD COLUMN IF NOT EXISTS 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);

CREATE INDEX IF NOT EXISTS quote_judge_receipts_receipt_id_idx
    ON quote_judge_receipts (receipt_id);
