-- Append-only audit trail for domain-level archive activity.
-- Enables dashboard queries (Family Pulse, activity feed, resume card) in #271.

CREATE TABLE audit_log (
    id          UUID        PRIMARY KEY DEFAULT gen_random_uuid(),
    happened_at TIMESTAMPTZ NOT NULL    DEFAULT now(),
    -- ON DELETE SET NULL is by design: GDPR right-to-erasure. Deleted users' events
    -- retain their timestamp and kind but lose actor attribution.
    actor_id    UUID        REFERENCES users(id) ON DELETE SET NULL,
    kind        VARCHAR(50) NOT NULL,
    document_id UUID        REFERENCES documents(id) ON DELETE CASCADE,
    payload     JSONB
);

CREATE INDEX idx_audit_log_happened_at ON audit_log (happened_at DESC);
CREATE INDEX idx_audit_log_document_id ON audit_log (document_id);
CREATE INDEX idx_audit_log_actor_id    ON audit_log (actor_id);
CREATE INDEX idx_audit_log_kind        ON audit_log (kind);

-- Enforce append-only at the database layer: the application role may INSERT
-- but must not UPDATE or DELETE audit rows.
-- NOTE: This REVOKE is a no-op when the current user is the table owner.
-- PostgreSQL owners retain all privileges regardless of REVOKE. The append-only
-- guarantee is enforced at the application layer only.
REVOKE UPDATE, DELETE ON audit_log FROM CURRENT_USER;
