-- Perfil de administrador: gestion de catalogo (con foto), meta default por ejercicio,
-- y puntaje asignable a insignias/logros.

alter table public.profiles add column is_admin boolean not null default false;

alter table public.exercises add column image_url text;
alter table public.exercises add column default_target_sets int not null default 4;
alter table public.exercises add column default_target_reps int not null default 12;

alter table public.badges add column points_reward int not null default 0;

-- Las insignias ahora pueden otorgar puntos directamente al desbloquearse.
alter table public.points_events drop constraint points_events_event_type_check;
alter table public.points_events add constraint points_events_event_type_check
  check (event_type in ('attendance', 'volume', 'body_fat', 'muscle_gain', 'evaluation_logged', 'achievement'));

create or replace function public.is_admin(uid uuid)
returns boolean
language sql
stable
security definer
set search_path = public
as $$
  select coalesce((select p.is_admin from public.profiles p where p.id = uid), false);
$$;

revoke all on function public.is_admin(uuid) from public;
grant execute on function public.is_admin(uuid) to authenticated;

-- Catalogo de ejercicios: antes solo lectura para todos, ahora escritura para administradores.
create policy "exercises: admin insert" on public.exercises
  for insert with check (public.is_admin(auth.uid()));

create policy "exercises: admin update" on public.exercises
  for update using (public.is_admin(auth.uid())) with check (public.is_admin(auth.uid()));

create policy "exercises: admin delete" on public.exercises
  for delete using (public.is_admin(auth.uid()));

-- Insignias: el catalogo lo carga la migracion, pero el puntaje lo puede ajustar el administrador.
create policy "badges: admin update points" on public.badges
  for update using (public.is_admin(auth.uid())) with check (public.is_admin(auth.uid()));

-- Bucket de Storage para las fotos de las maquinas, tomadas con la camara desde el perfil admin.
insert into storage.buckets (id, name, public)
values ('exercise-photos', 'exercise-photos', true)
on conflict (id) do nothing;

create policy "exercise-photos: public read" on storage.objects
  for select using (bucket_id = 'exercise-photos');

create policy "exercise-photos: admin write" on storage.objects
  for insert with check (bucket_id = 'exercise-photos' and public.is_admin(auth.uid()));

create policy "exercise-photos: admin update" on storage.objects
  for update using (bucket_id = 'exercise-photos' and public.is_admin(auth.uid()));

create policy "exercise-photos: admin delete" on storage.objects
  for delete using (bucket_id = 'exercise-photos' and public.is_admin(auth.uid()));
