{"-- Fix RLS policies for aman_instances table to ensure proper access

-- Drop existing policies
DROP POLICY IF EXISTS \"Admins and managers can manage Aman instances\" ON aman_instances","DROP POLICY IF EXISTS \"Users can view Aman instances in their organization\" ON aman_instances","-- Create new policies with better organization access
CREATE POLICY \"Users can view Aman instances in their organization\" 
ON aman_instances 
FOR SELECT 
USING (
  EXISTS (
    SELECT 1 FROM user_roles ur 
    WHERE ur.user_id = auth.uid() 
    AND ur.organization_id = aman_instances.organization_id
  )
)","CREATE POLICY \"Admins and managers can manage Aman instances\" 
ON aman_instances 
FOR ALL 
USING (
  EXISTS (
    SELECT 1 FROM user_roles ur 
    WHERE ur.user_id = auth.uid() 
    AND ur.organization_id = aman_instances.organization_id 
    AND ur.role = ANY(ARRAY['admin'::user_role, 'manager'::user_role])
  )
)
WITH CHECK (
  EXISTS (
    SELECT 1 FROM user_roles ur 
    WHERE ur.user_id = auth.uid() 
    AND ur.organization_id = aman_instances.organization_id 
    AND ur.role = ANY(ARRAY['admin'::user_role, 'manager'::user_role])
  )
)","-- Also allow super admin access
CREATE POLICY \"Super admin can manage all Aman instances\" 
ON aman_instances 
FOR ALL 
USING (is_current_user_super_admin())
WITH CHECK (is_current_user_super_admin())"}