{"-- Ensure the bucket exists (idempotent)
INSERT INTO storage.buckets (id, name, public)
VALUES ('form-attachments', 'form-attachments', true)
ON CONFLICT (id) DO NOTHING","-- Allow public read access to files in the form-attachments bucket (idempotent)
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_policies
    WHERE schemaname = 'storage'
      AND tablename = 'objects'
      AND policyname = 'Public can view form attachments'
  ) THEN
    CREATE POLICY \"Public can view form attachments\"
    ON storage.objects
    FOR SELECT
    USING (bucket_id = 'form-attachments');
  END IF;
END $$","-- Allow authenticated users to upload to their own folder: <user_id>/...
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_policies
    WHERE schemaname = 'storage'
      AND tablename = 'objects'
      AND policyname = 'Users can upload to their folder (form-attachments)'
  ) THEN
    CREATE POLICY \"Users can upload to their folder (form-attachments)\"
    ON storage.objects
    FOR INSERT
    WITH CHECK (
      bucket_id = 'form-attachments'
      AND auth.uid()::text = (storage.foldername(name))[1]
    );
  END IF;
END $$","-- Allow authenticated users to update files in their own folder
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_policies
    WHERE schemaname = 'storage'
      AND tablename = 'objects'
      AND policyname = 'Users can update their own files (form-attachments)'
  ) THEN
    CREATE POLICY \"Users can update their own files (form-attachments)\"
    ON storage.objects
    FOR UPDATE
    USING (
      bucket_id = 'form-attachments'
      AND auth.uid()::text = (storage.foldername(name))[1]
    );
  END IF;
END $$","-- Allow authenticated users to delete files in their own folder
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_policies
    WHERE schemaname = 'storage'
      AND tablename = 'objects'
      AND policyname = 'Users can delete their own files (form-attachments)'
  ) THEN
    CREATE POLICY \"Users can delete their own files (form-attachments)\"
    ON storage.objects
    FOR DELETE
    USING (
      bucket_id = 'form-attachments'
      AND auth.uid()::text = (storage.foldername(name))[1]
    );
  END IF;
END $$"}