-- =============================================================================
-- Migration: 20260420000007_notif_channels_saas_admin_insert
--
-- Fix: SaaS admin nao conseguia INSERT em notification_channels via /saas/whatsapp
-- porque a policy de insert exigia owner_id = auth.uid() e o saas_admin esta
-- inserindo em nome do tenant_admin (outro user). As policies de update/delete
-- ja tinham OR is_saas_admin() — o insert foi esquecido.
-- =============================================================================

DROP POLICY IF EXISTS "notif_channels_insert" ON public.notification_channels;

CREATE POLICY "notif_channels_insert" ON public.notification_channels
    FOR INSERT TO authenticated
    WITH CHECK (
        public.is_saas_admin()
        OR (
            owner_id = auth.uid()
            AND tenant_id IN (
                SELECT tm.tenant_id FROM public.tenant_members tm
                WHERE tm.user_id = auth.uid() AND tm.status = 'active'
            )
        )
    );

COMMENT ON POLICY "notif_channels_insert" ON public.notification_channels IS
    'SaaS admin pode inserir em nome de qualquer tenant; tenant_member insere pra si mesmo.';
