
-- Create profiles table
create table if not exists profiles (
  id uuid references auth.users on delete cascade primary key,
  role text not null default 'user' check (role in ('admin', 'user')),
  full_name text,
  created_at timestamp with time zone default timezone('utc'::text, now()) not null
);

-- Enable RLS for profiles
alter table profiles enable row level security;

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

create policy "Users can insert their own profile."
  on profiles for insert
  with check ( auth.uid() = id );

create policy "Users can update own profile."
  on profiles for update
  using ( auth.uid() = id );

-- Create site_settings table
create table if not exists site_settings (
  id bigint primary key generated always as identity,
  site_title text not null default 'ParaKasa',
  site_description text,
  contact_email text,
  contact_phone text,
  logo_url text,
  currency text default 'TRY',
  updated_at timestamp with time zone default timezone('utc'::text, now()) not null
);

-- Enable RLS for site_settings
alter table site_settings enable row level security;

-- Policies for site_settings
create policy "Site settings are viewable by everyone."
  on site_settings for select
  using ( true );

create policy "Only admins can update site settings."
  on site_settings for update
  using ( 
    exists (
      select 1 from profiles
      where profiles.id = auth.uid() and profiles.role = 'admin'
    )
  );

-- Initialize default site settings if empty
insert into site_settings (site_title, contact_email)
select 'ParaKasa', 'info@parakasa.com'
where not exists (select 1 from site_settings);
