-- Değişim Takip — veritabanı şeması
-- Supabase panelinde: SQL Editor → New query → bu dosyanın tamamını yapıştır → Run.
-- Birden fazla kez çalıştırmak güvenlidir.

-- ─────────────────────────────────────────────────────────────
-- Profiller: her giriş yapan kişi (admin veya öğrenci)
-- ─────────────────────────────────────────────────────────────
create table if not exists public.profiles (
  id            uuid primary key references auth.users (id) on delete cascade,
  email         text not null,
  full_name     text not null default '',
  role          text not null default 'student' check (role in ('admin', 'student')),
  -- Hedefler (yalnızca öğrenciler için anlamlı)
  start_date    date,
  start_weight  numeric(5, 1),
  goal_weight   numeric(5, 1),
  goal_date     date,
  calorie_goal  integer,
  step_goal     integer,
  protein_goal  integer,
  created_at    timestamptz not null default now()
);

-- ─────────────────────────────────────────────────────────────
-- Günlük kayıtlar
-- ─────────────────────────────────────────────────────────────
create table if not exists public.entries (
  id          bigint generated always as identity primary key,
  student_id  uuid not null references public.profiles (id) on delete cascade,
  day         date not null,
  weight      numeric(5, 1),
  steps       integer,
  calories    integer,
  protein     integer,
  fat         integer,
  carbs       integer,
  note        text,
  created_at  timestamptz not null default now(),
  updated_at  timestamptz not null default now(),
  unique (student_id, day)
);
create index if not exists entries_student_day on public.entries (student_id, day);

-- ─────────────────────────────────────────────────────────────
-- Fotoğraflar (dosyanın kendisi Storage'daki "photos" kovasında)
-- ─────────────────────────────────────────────────────────────
create table if not exists public.photos (
  id          bigint generated always as identity primary key,
  student_id  uuid not null references public.profiles (id) on delete cascade,
  taken_on    date not null,
  path        text not null,           -- photos kovasındaki yol: <student_id>/<dosya>
  created_at  timestamptz not null default now()
);
create index if not exists photos_student_day on public.photos (student_id, taken_on);

-- ─────────────────────────────────────────────────────────────
-- Yardımcı: istek yapan kişi admin mi?
-- security definer: RLS'e takılmadan profiles'a bakabilsin diye.
-- ─────────────────────────────────────────────────────────────
create or replace function public.is_admin()
returns boolean
language sql
stable
security definer
set search_path = public
as $$
  select exists (select 1 from public.profiles where id = auth.uid() and role = 'admin');
$$;

-- Yeni kullanıcı oluşunca profil satırı aç (davet ya da ilk giriş).
create or replace function public.handle_new_user()
returns trigger
language plpgsql
security definer
set search_path = public
as $$
begin
  insert into public.profiles (id, email, full_name)
  values (new.id, new.email, coalesce(new.raw_user_meta_data ->> 'full_name', ''))
  on conflict (id) do nothing;
  return new;
end;
$$;

drop trigger if exists on_auth_user_created on auth.users;
create trigger on_auth_user_created
  after insert on auth.users
  for each row execute function public.handle_new_user();

-- ─────────────────────────────────────────────────────────────
-- Satır güvenliği (RLS): öğrenci yalnızca kendini görür, admin herkesi.
-- Yazma yetkisi yalnızca adminde.
-- ─────────────────────────────────────────────────────────────
alter table public.profiles enable row level security;
alter table public.entries  enable row level security;
alter table public.photos   enable row level security;

drop policy if exists "profil: kendini veya admin okur" on public.profiles;
create policy "profil: kendini veya admin okur" on public.profiles
  for select using (id = auth.uid() or public.is_admin());

drop policy if exists "profil: admin günceller" on public.profiles;
create policy "profil: admin günceller" on public.profiles
  for update using (public.is_admin()) with check (public.is_admin());

drop policy if exists "kayıt: kendini veya admin okur" on public.entries;
create policy "kayıt: kendini veya admin okur" on public.entries
  for select using (student_id = auth.uid() or public.is_admin());

drop policy if exists "kayıt: admin yazar" on public.entries;
create policy "kayıt: admin yazar" on public.entries
  for all using (public.is_admin()) with check (public.is_admin());

drop policy if exists "foto: kendini veya admin okur" on public.photos;
create policy "foto: kendini veya admin okur" on public.photos
  for select using (student_id = auth.uid() or public.is_admin());

drop policy if exists "foto: admin yazar" on public.photos;
create policy "foto: admin yazar" on public.photos
  for all using (public.is_admin()) with check (public.is_admin());

-- Öğrenci kendi rolünü admin yapamasın: profiles'ta update yalnız adminde (yukarıda).

-- ─────────────────────────────────────────────────────────────
-- Storage: özel "photos" kovası
-- ─────────────────────────────────────────────────────────────
insert into storage.buckets (id, name, public)
values ('photos', 'photos', false)
on conflict (id) do nothing;

drop policy if exists "foto dosyası: sahibi veya admin okur" on storage.objects;
create policy "foto dosyası: sahibi veya admin okur" on storage.objects
  for select using (
    bucket_id = 'photos'
    and ((storage.foldername(name))[1] = auth.uid()::text or public.is_admin())
  );

drop policy if exists "foto dosyası: admin yükler" on storage.objects;
create policy "foto dosyası: admin yükler" on storage.objects
  for insert with check (bucket_id = 'photos' and public.is_admin());

drop policy if exists "foto dosyası: admin siler" on storage.objects;
create policy "foto dosyası: admin siler" on storage.objects
  for delete using (bucket_id = 'photos' and public.is_admin());
