-- Shared audit schema (generic event log usable by multiple modules)
-- Status: PROPOSED (2025-12-05)

CREATE SCHEMA IF NOT EXISTS audit;

CREATE TABLE IF NOT EXISTS audit.events (
    id BIGSERIAL PRIMARY KEY,
    tenant_id UUID NOT NULL,
    module TEXT NOT NULL,                 -- e.g., authority, scheduler, notify, issuer
    entity_type TEXT NOT NULL,            -- e.g., issuer, schedule, policy_pack
    entity_id UUID,
    action TEXT NOT NULL,                 -- e.g., create, update, delete
    actor TEXT,
    actor_type TEXT CHECK (actor_type IN ('user','service','system')),
    reason TEXT,
    details JSONB DEFAULT '{}'::jsonb,
    correlation_id TEXT,
    occurred_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_audit_module_time ON audit.events(module, occurred_at DESC);
CREATE INDEX IF NOT EXISTS idx_audit_tenant_time ON audit.events(tenant_id, occurred_at DESC);
CREATE INDEX IF NOT EXISTS idx_audit_entity ON audit.events(entity_type, entity_id);
