CREATE TABLE IF NOT EXISTS audit_log (
    id TEXT PRIMARY KEY,
    tenant_id TEXT NOT NULL,
    event_id TEXT NOT NULL,
    source_app TEXT NOT NULL DEFAULT 'bgp',
    action TEXT NOT NULL,
    severity TEXT NOT NULL DEFAULT 'info',
    actor_user_id TEXT,
    actor_email TEXT,
    actor_name TEXT,
    actor_api_key_prefix TEXT,
    target_type TEXT,
    target_id TEXT,
    summary TEXT NOT NULL,
    details_json JSONB,
    ip TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    portal_pushed_at TIMESTAMPTZ,
    CONSTRAINT audit_log_severity_chk CHECK (severity IN ('info', 'warning', 'critical')),
    CONSTRAINT audit_log_source_app_chk CHECK (source_app = 'bgp'),
    CONSTRAINT audit_log_summary_chk CHECK (length(trim(summary)) > 0)
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_audit_log_event_id ON audit_log (event_id);

CREATE INDEX IF NOT EXISTS idx_audit_log_tenant_created
    ON audit_log (tenant_id, created_at DESC);

CREATE INDEX IF NOT EXISTS idx_audit_log_tenant_action
    ON audit_log (tenant_id, action, created_at DESC);
