CREATE TABLE IF NOT EXISTS csv_analyses (
    tenant_key TEXT NOT NULL,
    analysis_id TEXT NOT NULL,
    question TEXT NOT NULL,
    answer TEXT NOT NULL,
    row_count INTEGER NOT NULL CHECK (row_count >= 0),
    column_count INTEGER NOT NULL CHECK (column_count >= 0),
    payload JSONB NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    PRIMARY KEY (tenant_key, analysis_id)
);

CREATE INDEX IF NOT EXISTS csv_analyses_tenant_updated_idx
    ON csv_analyses (tenant_key, updated_at DESC);

CREATE TABLE IF NOT EXISTS execution_receipts (
    tenant_key TEXT NOT NULL,
    receipt_id TEXT NOT NULL,
    analysis_id TEXT NOT NULL,
    skill_name TEXT NOT NULL,
    input_hash TEXT NOT NULL,
    payload JSONB NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    PRIMARY KEY (tenant_key, receipt_id),
    FOREIGN KEY (tenant_key, analysis_id)
        REFERENCES csv_analyses (tenant_key, analysis_id)
        ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS execution_receipts_tenant_analysis_idx
    ON execution_receipts (tenant_key, analysis_id, created_at DESC);
