-- ASA Foundation: immutable audit log
-- Append-only, actor/subject aware, reason-aware for impersonation.
-- No UPDATE or DELETE policies — log entries are permanent.

CREATE TABLE IF NOT EXISTS public.audit_log (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  actor_id UUID NOT NULL,
  actor_email TEXT,
  actor_role TEXT,
  subject_id UUID,
  subject_email TEXT,
  action TEXT NOT NULL,
  resource_type TEXT,
  resource_id TEXT,
  details JSONB DEFAULT '{}',
  reason TEXT,
  ip_address TEXT,
  user_agent TEXT,
  impersonation_session_id UUID,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Indexes for common queries
CREATE INDEX IF NOT EXISTS idx_audit_log_actor ON public.audit_log (actor_id);
CREATE INDEX IF NOT EXISTS idx_audit_log_subject ON public.audit_log (subject_id);
CREATE INDEX IF NOT EXISTS idx_audit_log_action ON public.audit_log (action);
CREATE INDEX IF NOT EXISTS idx_audit_log_created ON public.audit_log (created_at DESC);
CREATE INDEX IF NOT EXISTS idx_audit_log_resource ON public.audit_log (resource_type, resource_id);

-- RLS: audit log is append-only via service_role
ALTER TABLE public.audit_log ENABLE ROW LEVEL SECURITY;

-- Admins can read audit log (via server-side queries with service_role)
-- No INSERT/UPDATE/DELETE policies for regular users = immutable from app perspective
