-- Helper: retorna true si el usuario actual es platform_admin
CREATE OR REPLACE FUNCTION public.is_platform_admin()
RETURNS boolean
LANGUAGE sql SECURITY DEFINER
AS $$
  SELECT EXISTS (
    SELECT 1 FROM public.users
    WHERE id = auth.uid() AND platform_role = 'platform_admin'
  );
$$;

-- Eliminar política amplia de Sprint 4 Etapa 2
DROP POLICY IF EXISTS "authenticated_all_processes" ON public.processes;

-- Políticas granulares
CREATE POLICY "select_processes" ON public.processes
  FOR SELECT USING (
    public.is_platform_admin()
    OR owner_id = auth.uid()
    OR EXISTS (
      SELECT 1 FROM public.process_access
      WHERE process_id = processes.id
        AND (
          (grantee_type = 'user'  AND grantee_id = auth.uid())
          OR (grantee_type = 'group' AND grantee_id IN (
            SELECT group_id FROM public.group_memberships WHERE user_id = auth.uid()
          ))
        )
    )
  );

CREATE POLICY "insert_processes" ON public.processes
  FOR INSERT WITH CHECK (auth.uid() IS NOT NULL);

CREATE POLICY "update_processes" ON public.processes
  FOR UPDATE USING (
    public.is_platform_admin()
    OR owner_id = auth.uid()
    OR EXISTS (
      SELECT 1 FROM public.process_access
      WHERE process_id = processes.id
        AND permission = 'edit'
        AND (
          (grantee_type = 'user'  AND grantee_id = auth.uid())
          OR (grantee_type = 'group' AND grantee_id IN (
            SELECT group_id FROM public.group_memberships WHERE user_id = auth.uid()
          ))
        )
    )
  );

CREATE POLICY "delete_processes" ON public.processes
  FOR DELETE USING (public.is_platform_admin() OR owner_id = auth.uid());
