alter table public.organizations
  add column if not exists icon_url text;

insert into storage.buckets (id, name, public, file_size_limit, allowed_mime_types)
values (
  'organization-icons',
  'organization-icons',
  true,
  5242880,
  array['image/png', 'image/jpeg', 'image/webp', 'image/gif']
)
on conflict (id) do update
set
  public = excluded.public,
  file_size_limit = excluded.file_size_limit,
  allowed_mime_types = excluded.allowed_mime_types;

drop policy if exists "org_icons_public_read" on storage.objects;
create policy "org_icons_public_read"
  on storage.objects
  for select
  to public
  using (bucket_id = 'organization-icons');

drop policy if exists "org_icons_insert_admins" on storage.objects;
create policy "org_icons_insert_admins"
  on storage.objects
  for insert
  to authenticated
  with check (
    bucket_id = 'organization-icons'
    and owner_id = auth.uid()::text
    and public.org_role(split_part(name, '/', 1)) in ('owner', 'admin')
  );

drop policy if exists "org_icons_update_admins" on storage.objects;
create policy "org_icons_update_admins"
  on storage.objects
  for update
  to authenticated
  using (
    bucket_id = 'organization-icons'
    and public.org_role(split_part(name, '/', 1)) in ('owner', 'admin')
  )
  with check (
    bucket_id = 'organization-icons'
    and owner_id = auth.uid()::text
    and public.org_role(split_part(name, '/', 1)) in ('owner', 'admin')
  );

drop policy if exists "org_icons_delete_admins" on storage.objects;
create policy "org_icons_delete_admins"
  on storage.objects
  for delete
  to authenticated
  using (
    bucket_id = 'organization-icons'
    and public.org_role(split_part(name, '/', 1)) in ('owner', 'admin')
  );
