-- ============================================================
-- Fix: RLS notification_templates — acesso SaaS Admin
-- Admin precisa criar/editar/excluir templates globais (tenant_id IS NULL)
-- Agência PSI — 2026-03-22
-- ============================================================

-- SaaS Admin: acesso total (SELECT + INSERT + UPDATE + DELETE)
DROP POLICY IF EXISTS "notif_templates_admin_all" ON public.notification_templates;
CREATE POLICY "notif_templates_admin_all"
  ON public.notification_templates FOR ALL
  TO authenticated
  USING (
    EXISTS (SELECT 1 FROM public.saas_admins WHERE user_id = auth.uid())
  )
  WITH CHECK (
    EXISTS (SELECT 1 FROM public.saas_admins WHERE user_id = auth.uid())
  );

-- Tenant member: pode ler os globais + os do seu tenant
DROP POLICY IF EXISTS "notif_templates_read_global" ON public.notification_templates;
CREATE POLICY "notif_templates_read_global"
  ON public.notification_templates FOR SELECT
  TO authenticated
  USING (
    deleted_at IS NULL
    AND (
      (tenant_id IS NULL AND is_default = true)
      OR owner_id = auth.uid()
      OR public.is_tenant_member(tenant_id)
    )
  );

-- Tenant member: pode inserir/atualizar templates do seu tenant
DROP POLICY IF EXISTS "notif_templates_write_owner" ON public.notification_templates;
CREATE POLICY "notif_templates_write_owner"
  ON public.notification_templates FOR ALL
  TO authenticated
  USING (
    owner_id = auth.uid()
    OR public.is_tenant_member(tenant_id)
  )
  WITH CHECK (
    owner_id = auth.uid()
    OR public.is_tenant_member(tenant_id)
  );
