alter table public.profiles
  add column if not exists avatar_url text;

insert into storage.buckets (id, name, public)
  select 'avatars', 'avatars', true
  where not exists (select 1 from storage.buckets where id = 'avatars');

do $$
begin
  if not exists (select 1 from pg_policies where policyname = 'Avatar images are publicly accessible' and tablename = 'objects') then
    execute 'create policy "Avatar images are publicly accessible" on storage.objects for select using (bucket_id = ''avatars'')';
  end if;
  if not exists (select 1 from pg_policies where policyname = 'Users can upload their own avatar' and tablename = 'objects') then
    execute 'create policy "Users can upload their own avatar" on storage.objects for insert with check (bucket_id = ''avatars'' and auth.uid()::text = (storage.foldername(name))[1])';
  end if;
  if not exists (select 1 from pg_policies where policyname = 'Users can update their own avatar' and tablename = 'objects') then
    execute 'create policy "Users can update their own avatar" on storage.objects for update using (bucket_id = ''avatars'' and auth.uid()::text = (storage.foldername(name))[1])';
  end if;
end $$;
