{"-- Enable RLS on aman_instances table
ALTER TABLE public.aman_instances ENABLE ROW LEVEL SECURITY","-- Drop existing policies to avoid conflicts
DO $$
DECLARE r record;
BEGIN
  FOR r IN SELECT policyname FROM pg_policies WHERE tablename='aman_instances' AND schemaname='public' LOOP
    EXECUTE format('DROP POLICY %I ON public.aman_instances', r.policyname);
  END LOOP;
END $$","-- Create policies for aman_instances
CREATE POLICY \"aman_view_super_admin\" ON public.aman_instances FOR SELECT TO authenticated
USING (EXISTS (SELECT 1 FROM public.user_roles WHERE user_id = auth.uid() AND role = 'super_admin'))","CREATE POLICY \"aman_view_org_admin\" ON public.aman_instances FOR SELECT TO authenticated
USING (organization_id IN (SELECT organization_id FROM public.user_roles WHERE user_id = auth.uid() AND role IN ('admin', 'manager')))","CREATE POLICY \"aman_view_rep\" ON public.aman_instances FOR SELECT TO authenticated
USING (branch_id IN (SELECT branch_id FROM public.user_roles WHERE user_id = auth.uid() AND role = 'representative'))","CREATE POLICY \"aman_insert_super\" ON public.aman_instances FOR INSERT TO authenticated
WITH CHECK (EXISTS (SELECT 1 FROM public.user_roles WHERE user_id = auth.uid() AND role = 'super_admin'))","CREATE POLICY \"aman_insert_org\" ON public.aman_instances FOR INSERT TO authenticated
WITH CHECK (organization_id IN (SELECT organization_id FROM public.user_roles WHERE user_id = auth.uid() AND role IN ('admin', 'manager')))","CREATE POLICY \"aman_update_super\" ON public.aman_instances FOR UPDATE TO authenticated
USING (EXISTS (SELECT 1 FROM public.user_roles WHERE user_id = auth.uid() AND role = 'super_admin'))","CREATE POLICY \"aman_update_org\" ON public.aman_instances FOR UPDATE TO authenticated
USING (organization_id IN (SELECT organization_id FROM public.user_roles WHERE user_id = auth.uid() AND role IN ('admin', 'manager')))","CREATE POLICY \"aman_delete_super\" ON public.aman_instances FOR DELETE TO authenticated
USING (EXISTS (SELECT 1 FROM public.user_roles WHERE user_id = auth.uid() AND role = 'super_admin'))","CREATE POLICY \"aman_delete_org\" ON public.aman_instances FOR DELETE TO authenticated
USING (organization_id IN (SELECT organization_id FROM public.user_roles WHERE user_id = auth.uid() AND role IN ('admin', 'manager')))"}