-- Create products table
create table if not exists products (
  id bigint primary key generated always as identity,
  name text not null,
  category text not null,
  description text,
  image_url text,
  price decimal(10,2), -- Optional, validation can start without it
  created_at timestamp with time zone default timezone('utc'::text, now()) not null
);

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

-- Policies
-- 1. Public read access
create policy "Public products are viewable by everyone."
  on products for select
  using ( true );

-- 2. Admin write access (Only authenticated users for now, can be restricted to specific emails/roles later)
create policy "Authenticated users can insert products."
  on products for insert
  with check ( auth.role() = 'authenticated' );

create policy "Authenticated users can update products."
  on products for update
  using ( auth.role() = 'authenticated' );

create policy "Authenticated users can delete products."
  on products for delete
  using ( auth.role() = 'authenticated' );

-- Storage Bucket for Product Images
insert into storage.buckets (id, name, public) 
values ('product-images', 'product-images', true)
on conflict (id) do nothing;

create policy "Images are publicly accessible."
  on storage.objects for select
  using ( bucket_id = 'product-images' );

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

create policy "Authenticated users can delete images."
  on storage.objects for delete
  using ( bucket_id = 'product-images' and auth.role() = 'authenticated' );
