-- 026_immutable_audit_log.sql
--
-- Makes audit_log immutable — blocks DELETE and UPDATE.
-- Only INSERT is permitted (from the customers audit trigger).
--
-- Emergency override (requires explicit admin action):
--   ALTER TABLE audit_log DISABLE TRIGGER trg_protect_audit_log;
--   -- perform operation --
--   ALTER TABLE audit_log ENABLE TRIGGER trg_protect_audit_log;

CREATE OR REPLACE FUNCTION protect_audit_log()
RETURNS TRIGGER AS $$
BEGIN
  RAISE EXCEPTION 'audit_log is immutable — DELETE and UPDATE are forbidden. Contact system administrator.';
  RETURN NULL;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS trg_protect_audit_log ON audit_log;
CREATE TRIGGER trg_protect_audit_log
  BEFORE UPDATE OR DELETE ON audit_log
  FOR EACH ROW
  EXECUTE FUNCTION protect_audit_log();
