{"-- Drop existing policies to fix the permission issue
DROP POLICY IF EXISTS \"Admins and managers can insert cameras in their organization\" ON public.cameras","DROP POLICY IF EXISTS \"Super admin can insert cameras\" ON public.cameras","-- Create a more permissive INSERT policy that handles authentication properly
CREATE POLICY \"Users with admin/manager role can insert cameras\"
ON public.cameras
FOR INSERT
TO authenticated
WITH CHECK (
  -- Super admin can add cameras anywhere
  is_current_user_super_admin() 
  OR
  -- Regular admins/managers can add cameras in their organization
  EXISTS (
    SELECT 1
    FROM public.user_roles ur
    JOIN public.branches b ON b.organization_id = ur.organization_id
    WHERE ur.user_id = auth.uid()
      AND ur.role IN ('admin', 'manager')
      AND b.id = branch_id
  )
)","-- Also update the SELECT policy to be more permissive for troubleshooting
DROP POLICY IF EXISTS \"Users can view cameras in their organization\" ON public.cameras","CREATE POLICY \"Users can view cameras in their organization\"
ON public.cameras
FOR SELECT
TO authenticated
USING (
  -- Super admin can view all
  is_current_user_super_admin()
  OR
  -- Regular users can view cameras in their organization
  EXISTS (
    SELECT 1
    FROM public.branches b
    JOIN public.user_roles ur ON ur.organization_id = b.organization_id
    WHERE b.id = cameras.branch_id
      AND ur.user_id = auth.uid()
  )
)"}