CREATE TABLE IF NOT EXISTS contracts (
    id BIGSERIAL PRIMARY KEY,
    tenant_key TEXT NOT NULL,
    contract_id TEXT NOT NULL,
    title TEXT NOT NULL,
    source_text_hash TEXT NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT contracts_tenant_contract_key UNIQUE (tenant_key, contract_id)
);

CREATE TABLE IF NOT EXISTS contract_deadlines (
    id BIGSERIAL PRIMARY KEY,
    contract_pk BIGINT NOT NULL REFERENCES contracts(id) ON DELETE CASCADE,
    kind TEXT NOT NULL CHECK (kind IN ('renewal', 'notice')),
    deadline_date DATE NOT NULL,
    source_text TEXT,
    rationale TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS contract_deadlines_contract_idx
    ON contract_deadlines (contract_pk, deadline_date, kind);

CREATE TABLE IF NOT EXISTS execution_receipts (
    id BIGSERIAL PRIMARY KEY,
    receipt_id TEXT NOT NULL UNIQUE,
    tenant_key TEXT NOT NULL,
    contract_id TEXT,
    tool_name TEXT NOT NULL,
    task_id TEXT,
    input_hash TEXT NOT NULL,
    result_hash TEXT NOT NULL,
    status TEXT NOT NULL CHECK (status IN ('ok', 'error')),
    payload JSONB NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS execution_receipts_tenant_contract_idx
    ON execution_receipts (tenant_key, contract_id, created_at DESC);
