CREATE TABLE IF NOT EXISTS invoice_cases (
    id BIGSERIAL PRIMARY KEY,
    tenant_key TEXT NOT NULL,
    case_id TEXT NOT NULL,
    invoice_count INTEGER NOT NULL DEFAULT 0,
    duplicate_count INTEGER NOT NULL DEFAULT 0,
    total_mismatch_count INTEGER NOT NULL DEFAULT 0,
    invoices JSONB NOT NULL DEFAULT '[]'::jsonb,
    duplicates JSONB NOT NULL DEFAULT '[]'::jsonb,
    total_mismatches JSONB NOT NULL DEFAULT '[]'::jsonb,
    decisions JSONB NOT NULL DEFAULT '[]'::jsonb,
    receipt JSONB NOT NULL DEFAULT '{}'::jsonb,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (tenant_key, case_id)
);

CREATE INDEX IF NOT EXISTS invoice_cases_tenant_updated_idx
    ON invoice_cases (tenant_key, updated_at DESC);

CREATE INDEX IF NOT EXISTS invoice_cases_tenant_counts_idx
    ON invoice_cases (tenant_key, duplicate_count, total_mismatch_count);

CREATE TABLE IF NOT EXISTS invoice_execution_receipts (
    id BIGSERIAL PRIMARY KEY,
    tenant_key TEXT NOT NULL,
    receipt_id TEXT NOT NULL,
    case_id TEXT NOT NULL,
    skill TEXT NOT NULL,
    input_hash TEXT NOT NULL,
    receipt JSONB NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (tenant_key, receipt_id)
);

CREATE INDEX IF NOT EXISTS invoice_receipts_case_idx
    ON invoice_execution_receipts (tenant_key, case_id, created_at DESC);
