-- 004_ledger_attestations.sql
-- LEDGER-OBS-54-001: storage for attestation verification exports

BEGIN;

CREATE TABLE IF NOT EXISTS ledger_attestations (
    tenant_id           text        NOT NULL,
    attestation_id      uuid        NOT NULL,
    artifact_id         text        NOT NULL,
    finding_id          text        NULL,
    verification_status text        NOT NULL,
    verification_time   timestamptz NOT NULL,
    dsse_digest         text        NOT NULL,
    rekor_entry_id      text        NULL,
    evidence_bundle_ref text        NULL,
    ledger_event_id     uuid        NOT NULL,
    recorded_at         timestamptz NOT NULL,
    merkle_leaf_hash    text        NOT NULL,
    root_hash           text        NOT NULL,
    cycle_hash          text        NOT NULL,
    projection_version  text        NOT NULL
);

ALTER TABLE ledger_attestations
    ADD CONSTRAINT pk_ledger_attestations PRIMARY KEY (tenant_id, attestation_id);

CREATE INDEX IF NOT EXISTS ix_ledger_attestations_recorded
    ON ledger_attestations (tenant_id, recorded_at, attestation_id);

CREATE INDEX IF NOT EXISTS ix_ledger_attestations_artifact
    ON ledger_attestations (tenant_id, artifact_id, recorded_at DESC);

CREATE INDEX IF NOT EXISTS ix_ledger_attestations_finding
    ON ledger_attestations (tenant_id, finding_id, recorded_at DESC)
    WHERE finding_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS ix_ledger_attestations_status
    ON ledger_attestations (tenant_id, verification_status, recorded_at DESC);

COMMIT;
