-- Additive QuoteJudge v1 schema. Keep this compatible with older app_records-only deployments.
CREATE TABLE IF NOT EXISTS quote_judge_comparisons (
    id BIGSERIAL PRIMARY KEY,
    tenant_key TEXT NOT NULL,
    comparison_id TEXT NOT NULL,
    recommendation_vendor TEXT NOT NULL,
    result_json JSONB NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (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 INDEX IF NOT EXISTS quote_judge_comparisons_recommendation_idx
    ON quote_judge_comparisons (tenant_key, recommendation_vendor);

CREATE TABLE IF NOT EXISTS quote_judge_receipts (
    id BIGSERIAL PRIMARY KEY,
    tenant_key TEXT NOT NULL,
    comparison_id TEXT,
    skill_name TEXT NOT NULL,
    receipt_json JSONB NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

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

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

ALTER TABLE app_records ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
