-- Enable RLS on storage.buckets
alter table if exists storage.buckets enable row level security;

-- Drop existing policies if they exist
drop policy if exists "Super admin has full access to buckets" on storage.buckets;
drop policy if exists "Users can create their own buckets" on storage.buckets;
drop policy if exists "Users can view their own buckets" on storage.buckets;

-- Create new policies with proper permissions
create policy "Super admin has full access to buckets"
on storage.buckets for all
using (
    current_user = 'service_role' 
    or current_user = 'supabase_admin' 
    or exists (
        select 1 from public.profiles 
        where id = auth.uid() 
        and user_type = 'admin'
    )
);

-- Allow authenticated users to create buckets
create policy "Users can create their own buckets"
on storage.buckets for insert
to authenticated
with check (
    owner::text = auth.uid()::text
    or exists (
        select 1 from public.profiles 
        where id = auth.uid() 
        and user_type = 'admin'
    )
);

-- Allow users to view buckets they own or public buckets
create policy "Users can view their own buckets"
on storage.buckets for select
to authenticated
using (
    owner::text = auth.uid()::text
    or exists (
        select 1 from public.profiles 
        where id = auth.uid() 
        and user_type = 'admin'
    )
);

-- Grant necessary permissions
grant all on storage.buckets to authenticated;
grant all on storage.objects to authenticated; 