-- Create sliders table
create table if not exists sliders (
  id uuid default gen_random_uuid() primary key,
  title text not null,
  description text,
  image_url text not null,
  link text,
  "order" integer default 0,
  is_active boolean default true,
  created_at timestamp with time zone default timezone('utc'::text, now()) not null
);

-- Enable RLS
alter table sliders enable row level security;

-- Policies for Sliders Table
create policy "Public sliders are viewable by everyone."
  on sliders for select
  using ( true );

create policy "Admins can insert sliders."
  on sliders for insert
  with check (
    exists (
      select 1 from profiles
      where profiles.id = auth.uid() and profiles.role = 'admin'
    )
  );

create policy "Admins can update sliders."
  on sliders for update
  using (
    exists (
      select 1 from profiles
      where profiles.id = auth.uid() and profiles.role = 'admin'
    )
  );

create policy "Admins can delete sliders."
  on sliders for delete
  using (
    exists (
      select 1 from profiles
      where profiles.id = auth.uid() and profiles.role = 'admin'
    )
  );

-- STORAGE POLICIES (Assuming bucket 'images' exists)
-- You must create the 'images' bucket in Supabase Dashboard manually if not exists, 
-- or we can try to insert it via SQL if extensions allow, but usually dashboard is safer for buckets.
-- Below policies assume the bucket is named 'images' and is set to PUBLIC.

-- 1. Allow public read access to everyone
create policy "Public Access"
on storage.objects for select
using ( bucket_id = 'images' );

-- 2. Allow authenticated admins to upload
create policy "Admin Upload"
on storage.objects for insert
with check (
  bucket_id = 'images' and
  exists (
    select 1 from profiles
    where profiles.id = auth.uid() and profiles.role = 'admin'
  )
);

-- 3. Allow admins to update/delete their images (or all images)
create policy "Admin Update Delete"
on storage.objects for update
using (
  bucket_id = 'images' and
  exists (
    select 1 from profiles
    where profiles.id = auth.uid() and profiles.role = 'admin'
  )
);

create policy "Admin Delete"
on storage.objects for delete
using (
  bucket_id = 'images' and
  exists (
    select 1 from profiles
    where profiles.id = auth.uid() and profiles.role = 'admin'
  )
);
