-- Assessments table for PAT Stats
create table if not exists public.assessments (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users(id) on delete cascade,
  pat_type text not null,
  datum date not null,
  name text not null,
  exercises jsonb not null default '[]'::jsonb,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

-- Keep updated_at current
create or replace function public.set_updated_at()
returns trigger as $$
begin
  new.updated_at = now();
  return new;
end;
$$ language plpgsql;

drop trigger if exists trg_assessments_updated_at on public.assessments;
create trigger trg_assessments_updated_at
before update on public.assessments
for each row execute function public.set_updated_at();

-- Row Level Security
alter table public.assessments enable row level security;

-- Policies: authenticated users manage only their own rows
create policy if not exists "Allow users to insert own assessments"
on public.assessments
for insert with check (auth.uid() = user_id);

create policy if not exists "Allow users to select own assessments"
on public.assessments
for select using (auth.uid() = user_id);

create policy if not exists "Allow users to update own assessments"
on public.assessments
for update using (auth.uid() = user_id);

create policy if not exists "Allow users to delete own assessments"
on public.assessments
for delete using (auth.uid() = user_id);

-- Helpful index
create index if not exists idx_assessments_user_id_created_at
on public.assessments (user_id, created_at desc);
