-- ============================================================
-- Migration 004 / ETAPA_AUTH 4.2
-- Tabla user_roles + hook de custom claims para JWT
--
-- Después de aplicar esta migración, el director debe:
--   1. Agregar en Dokploy (servicio supabase-auth):
--        GOTRUE_HOOKS_CUSTOM_ACCESS_TOKEN_ENABLED=true
--        GOTRUE_HOOKS_CUSTOM_ACCESS_TOKEN_URI=pg-functions://postgres/public/custom_access_token_hook
--   2. Reiniciar el servicio supabase-auth (NO la app Next.js).
-- ============================================================

-- ── 1. Tabla user_roles ──────────────────────────────────────
CREATE TABLE public.user_roles (
  user_id  uuid PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
  app_role text NOT NULL CHECK (app_role IN ('platform_admin', 'org_admin')),
  org_id   uuid REFERENCES public.organizations(id)
);

ALTER TABLE public.user_roles ENABLE ROW LEVEL SECURITY;

-- El usuario ve su propio rol; platform_admin ve todos
CREATE POLICY "user_roles_select_own"
  ON public.user_roles
  FOR SELECT
  TO authenticated
  USING (
    user_id = auth.uid()
    OR public.current_app_role() = 'platform_admin'
  );

-- ── 2. Extender policies existentes para incluir platform_admin ──

-- organizations
DROP POLICY IF EXISTS "org_select_own" ON public.organizations;
CREATE POLICY "org_select_own"
  ON public.organizations
  FOR SELECT
  TO authenticated
  USING (
    public.current_app_role() IN ('analyst', 'platform_admin')
    OR (
      public.current_app_role() = 'org_admin'
      AND id = public.current_org_id()
    )
  );

-- surveys (no tocar surveys_select_live_anon — sigue igual)
DROP POLICY IF EXISTS "surveys_select_auth" ON public.surveys;
CREATE POLICY "surveys_select_auth"
  ON public.surveys
  FOR SELECT
  TO authenticated
  USING (
    public.current_app_role() IN ('analyst', 'platform_admin')
    OR (
      public.current_app_role() = 'org_admin'
      AND org_id = public.current_org_id()
    )
  );

-- questions (no tocar questions_select_live — sigue igual)
DROP POLICY IF EXISTS "questions_select_auth" ON public.questions;
CREATE POLICY "questions_select_auth"
  ON public.questions
  FOR SELECT
  TO authenticated
  USING (
    public.current_app_role() IN ('analyst', 'platform_admin')
    OR (
      public.current_app_role() = 'org_admin'
      AND EXISTS (
        SELECT 1 FROM public.surveys s
        WHERE s.id = survey_id
          AND s.org_id = public.current_org_id()
      )
    )
  );

-- ── 3. Nuevas policies SELECT para platform_admin (responses/answers no tenían) ──
CREATE POLICY "responses_select_platform_admin"
  ON public.responses
  FOR SELECT
  TO authenticated
  USING (public.current_app_role() IN ('analyst', 'platform_admin'));

CREATE POLICY "answers_select_platform_admin"
  ON public.answers
  FOR SELECT
  TO authenticated
  USING (public.current_app_role() IN ('analyst', 'platform_admin'));

-- ── 4. Hook de custom claims ─────────────────────────────────
-- Inyecta app_role y org_id en el JWT en cada emisión de token.
-- SECURITY DEFINER + search_path garantiza que bypasea RLS para leer user_roles.
CREATE OR REPLACE FUNCTION public.custom_access_token_hook(event jsonb)
RETURNS jsonb
LANGUAGE plpgsql
STABLE
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
  claims jsonb;
  v_role text;
  v_org  uuid;
BEGIN
  claims := event -> 'claims';

  SELECT app_role, org_id
    INTO v_role, v_org
    FROM public.user_roles
   WHERE user_id = (event ->> 'user_id')::uuid;

  IF v_role IS NOT NULL THEN
    claims := jsonb_set(claims, '{app_role}', to_jsonb(v_role));
    IF v_org IS NOT NULL THEN
      claims := jsonb_set(claims, '{org_id}', to_jsonb(v_org::text));
    END IF;
  END IF;

  RETURN jsonb_set(event, '{claims}', claims);
END;
$$;

-- GoTrue necesita EXECUTE para llamar la función y SELECT para que el SECURITY DEFINER
-- pueda leer user_roles internamente (aunque SECURITY DEFINER corre como postgres,
-- el grant explicito documenta la intención y protege contra cambios de ownership).
GRANT EXECUTE ON FUNCTION public.custom_access_token_hook(jsonb) TO supabase_auth_admin;
GRANT SELECT ON public.user_roles TO supabase_auth_admin;
