-- Create storage buckets for audio files and cover images
insert into storage.buckets (id, name, public)
values
  ('podcasts', 'podcasts', true),
  ('covers', 'covers', true)
on conflict (id) do nothing;

-- Allow anyone to read files (public buckets)
create policy "Public read access on podcasts" on storage.objects
  for select using (bucket_id = 'podcasts');

create policy "Public read access on covers" on storage.objects
  for select using (bucket_id = 'covers');

-- Allow authenticated users to upload files
create policy "Authenticated users can upload podcasts" on storage.objects
  for insert with check (bucket_id = 'podcasts' and auth.role() = 'authenticated');

create policy "Authenticated users can upload covers" on storage.objects
  for insert with check (bucket_id = 'covers' and auth.role() = 'authenticated');

-- Allow users to update/delete their own files
create policy "Users can update own podcast files" on storage.objects
  for update using (bucket_id = 'podcasts' and auth.uid()::text = (storage.foldername(name))[1]);

create policy "Users can delete own podcast files" on storage.objects
  for delete using (bucket_id = 'podcasts' and auth.uid()::text = (storage.foldername(name))[1]);

create policy "Users can update own cover files" on storage.objects
  for update using (bucket_id = 'covers' and auth.uid()::text = (storage.foldername(name))[1]);

create policy "Users can delete own cover files" on storage.objects
  for delete using (bucket_id = 'covers' and auth.uid()::text = (storage.foldername(name))[1]);
