
UPDATE storage.buckets SET public = false WHERE id = 'customer-images';

DROP POLICY IF EXISTS "Staff can read customer images" ON storage.objects;
CREATE POLICY "Staff can read customer images" ON storage.objects FOR SELECT TO authenticated
USING (bucket_id = 'customer-images' AND public.is_staff(auth.uid()));

DROP POLICY IF EXISTS "Staff can upload customer images" ON storage.objects;
CREATE POLICY "Staff can upload customer images" ON storage.objects FOR INSERT TO authenticated
WITH CHECK (bucket_id = 'customer-images' AND public.is_staff(auth.uid()));

DROP POLICY IF EXISTS "Staff can update customer images" ON storage.objects;
CREATE POLICY "Staff can update customer images" ON storage.objects FOR UPDATE TO authenticated
USING (bucket_id = 'customer-images' AND public.is_staff(auth.uid()));

DROP POLICY IF EXISTS "Staff can delete customer images" ON storage.objects;
CREATE POLICY "Staff can delete customer images" ON storage.objects FOR DELETE TO authenticated
USING (bucket_id = 'customer-images' AND public.is_staff(auth.uid()));

DROP POLICY IF EXISTS "Users can insert own profile" ON public.profiles;
CREATE POLICY "Users can insert own profile" ON public.profiles FOR INSERT TO authenticated
WITH CHECK (auth.uid() = id AND role = 'user');

DROP POLICY IF EXISTS status_log_select_auth ON public.sales_order_status_log;
DROP POLICY IF EXISTS status_log_insert_auth ON public.sales_order_status_log;
CREATE POLICY status_log_select_staff ON public.sales_order_status_log FOR SELECT TO authenticated
USING (public.is_staff(auth.uid()));
CREATE POLICY status_log_insert_staff ON public.sales_order_status_log FOR INSERT TO authenticated
WITH CHECK (public.is_staff(auth.uid()));

DROP POLICY IF EXISTS "Staff can view sms settings" ON public.sms_settings;
CREATE POLICY "Admins can view sms settings" ON public.sms_settings FOR SELECT TO authenticated
USING (public.has_role(auth.uid(), 'admin'::app_role));

DO $$
DECLARE r record;
BEGIN
  FOR r IN
    SELECT p.oid::regprocedure::text AS sig
    FROM pg_proc p JOIN pg_namespace n ON p.pronamespace = n.oid
    WHERE n.nspname = 'public' AND p.prosecdef = true
  LOOP
    EXECUTE format('REVOKE EXECUTE ON FUNCTION %s FROM PUBLIC, anon', r.sig);
  END LOOP;
END$$;
