{"-- Drop existing policies to recreate them properly
DROP POLICY IF EXISTS \"Org admins/managers can manage form distribution settings\" ON public.form_distribution_settings","DROP POLICY IF EXISTS \"Org members can view form distribution settings\" ON public.form_distribution_settings","DROP POLICY IF EXISTS \"Super admin can manage all form distribution settings\" ON public.form_distribution_settings","-- Enable RLS if not already enabled
ALTER TABLE public.form_distribution_settings ENABLE ROW LEVEL SECURITY","-- Create proper RLS policies
-- Allow organization admins and managers to manage distribution settings
CREATE POLICY \"Org admins/managers can manage form distribution settings\"
ON public.form_distribution_settings
FOR ALL
TO authenticated
USING (
  EXISTS (
    SELECT 1 FROM public.form_assignments fa
    JOIN public.user_roles ur ON ur.organization_id = fa.organization_id
    WHERE fa.workflow_form_id = form_distribution_settings.workflow_form_id
    AND ur.user_id = auth.uid()
    AND ur.role IN ('admin', 'manager')
  )
)
WITH CHECK (
  EXISTS (
    SELECT 1 FROM public.form_assignments fa
    JOIN public.user_roles ur ON ur.organization_id = fa.organization_id
    WHERE fa.workflow_form_id = form_distribution_settings.workflow_form_id
    AND ur.user_id = auth.uid()
    AND ur.role IN ('admin', 'manager')
  )
)","-- Allow organization members to view distribution settings (read-only access)
CREATE POLICY \"Org members can view form distribution settings\"
ON public.form_distribution_settings
FOR SELECT
TO authenticated
USING (
  EXISTS (
    SELECT 1 FROM public.form_assignments fa
    JOIN public.user_roles ur ON ur.organization_id = fa.organization_id
    WHERE fa.workflow_form_id = form_distribution_settings.workflow_form_id
    AND ur.user_id = auth.uid()
  )
)","-- Allow super admin full access
CREATE POLICY \"Super admin can manage all form distribution settings\"
ON public.form_distribution_settings
FOR ALL
TO authenticated
USING (public.is_current_user_super_admin())
WITH CHECK (public.is_current_user_super_admin())"}