-- ASA Foundation: impersonation sessions (hybrid b+c model)
-- Admin session stays admin session. Impersonation is app-layer server-side context.
-- Every impersonated action is audit-logged with actor + subject chain.

CREATE TABLE IF NOT EXISTS public.impersonation_sessions (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  actor_admin_id UUID NOT NULL REFERENCES auth.users(id),
  subject_user_id UUID NOT NULL REFERENCES auth.users(id),
  reason TEXT NOT NULL,
  started_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  expires_at TIMESTAMPTZ NOT NULL,
  stopped_at TIMESTAMPTZ,
  is_active BOOLEAN GENERATED ALWAYS AS (stopped_at IS NULL AND expires_at > now()) STORED,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_impersonation_actor ON public.impersonation_sessions (actor_admin_id);
CREATE INDEX IF NOT EXISTS idx_impersonation_active ON public.impersonation_sessions (is_active) WHERE is_active = true;

-- RLS: only accessible via service_role (backend)
ALTER TABLE public.impersonation_sessions ENABLE ROW LEVEL SECURITY;
