-- version: 9
-- SP11: tamper-evident hash-chained audit_log
--
-- Each row carries a SHA-256 hash of (id, event_type, entity_type,
-- entity_id, actor, payload_json, created_at, prev_hash). The prev_hash
-- field chains the row to the previous row's hash — a tamper-evident
-- Merkle-like chain (no tree, just a list).
--
-- Append-only by convention: no UPDATE/DELETE in the application code.
-- Compliance: HIPAA §164.316(b)(2) requires 6-year retention. We don't
-- enforce retention in the schema (no TTL), but a separate vacuum
-- job (out of scope here) can prune rows older than 6 years after
-- exporting them to cold storage.
--
-- Indexes: (entity_type, entity_id) for "show me the audit trail for
-- this claim"; (event_type) for "show me all clearhouse.submitted
-- events"; (created_at) for time-range scans.

CREATE TABLE audit_log (
    id            INTEGER PRIMARY KEY AUTOINCREMENT,
    event_type    TEXT NOT NULL,
    entity_type   TEXT NOT NULL,
    entity_id     TEXT NOT NULL,
    actor         TEXT NOT NULL DEFAULT 'system',
    payload_json  TEXT,
    created_at    TEXT NOT NULL,
    prev_hash     TEXT NOT NULL,
    hash          TEXT NOT NULL
);

CREATE INDEX idx_audit_log_entity ON audit_log(entity_type, entity_id);
CREATE INDEX idx_audit_log_event_type ON audit_log(event_type);
CREATE INDEX idx_audit_log_created_at ON audit_log(created_at);
