insert into storage.buckets (id, name, public, file_size_limit, allowed_mime_types)
values
  (
    '1688_screenshots',
    '1688_screenshots',
    true,
    209715200,
    array['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif']::text[]
  ),
  (
    'screenshots',
    'screenshots',
    true,
    209715200,
    array['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif']::text[]
  )
on conflict (id) do update
set
  name = excluded.name,
  public = excluded.public,
  file_size_limit = excluded.file_size_limit,
  allowed_mime_types = excluded.allowed_mime_types;

do $$
begin
  if not exists (
    select 1
    from pg_policies
    where schemaname = 'storage'
      and tablename = 'objects'
      and policyname = 'search_images_public_select'
  ) then
    create policy search_images_public_select
      on storage.objects
      for select
      to anon, authenticated
      using (bucket_id = any (array['1688_screenshots', 'screenshots']));
  end if;

  if not exists (
    select 1
    from pg_policies
    where schemaname = 'storage'
      and tablename = 'objects'
      and policyname = 'search_images_authenticated_insert'
  ) then
    create policy search_images_authenticated_insert
      on storage.objects
      for insert
      to authenticated
      with check (bucket_id = any (array['1688_screenshots', 'screenshots']));
  end if;

  if not exists (
    select 1
    from pg_policies
    where schemaname = 'storage'
      and tablename = 'objects'
      and policyname = 'search_images_authenticated_update'
  ) then
    create policy search_images_authenticated_update
      on storage.objects
      for update
      to authenticated
      using (bucket_id = any (array['1688_screenshots', 'screenshots']))
      with check (bucket_id = any (array['1688_screenshots', 'screenshots']));
  end if;

  if not exists (
    select 1
    from pg_policies
    where schemaname = 'storage'
      and tablename = 'objects'
      and policyname = 'search_images_authenticated_delete'
  ) then
    create policy search_images_authenticated_delete
      on storage.objects
      for delete
      to authenticated
      using (bucket_id = any (array['1688_screenshots', 'screenshots']));
  end if;
end $$;
