-- Fase 2: motor de puntos e insignias del avatar.
-- points_events es un ledger inmutable (no un contador) para poder auditar de donde salio cada punto.

create table public.points_events (
  id bigint generated always as identity primary key,
  user_id uuid not null references auth.users (id) on delete cascade,
  event_type text not null check (event_type in ('attendance', 'volume', 'body_fat', 'muscle_gain', 'evaluation_logged')),
  points int not null,
  metadata jsonb,
  created_at timestamptz not null default now()
);

create table public.badges (
  code text primary key,
  name text not null,
  description text not null
);

create table public.user_badges (
  user_id uuid not null references auth.users (id) on delete cascade,
  badge_code text not null references public.badges (code),
  unlocked_at timestamptz not null default now(),
  primary key (user_id, badge_code)
);

alter table public.points_events enable row level security;
alter table public.user_badges enable row level security;
alter table public.badges enable row level security;

create policy "points_events: owner full access" on public.points_events
  for all using (auth.uid() = user_id) with check (auth.uid() = user_id);

create policy "user_badges: owner full access" on public.user_badges
  for all using (auth.uid() = user_id) with check (auth.uid() = user_id);

create policy "badges: authenticated read" on public.badges
  for select using (auth.role() = 'authenticated');

insert into public.badges (code, name, description) values
  ('first_session', 'Primer entreno', 'Completaste tu primera sesion de entrenamiento.'),
  ('five_sessions', 'Constancia', 'Completaste 5 sesiones de entrenamiento.'),
  ('twenty_sessions', 'Habito de hierro', 'Completaste 20 sesiones de entrenamiento.'),
  ('first_evaluation', 'Primer pesaje', 'Registraste tu primera evaluacion corporal.'),
  ('fat_burner', 'Quema grasa', 'Bajaste al menos 2% de grasa corporal desde tu primera evaluacion.'),
  ('muscle_gainer', 'Ganancia muscular', 'Subiste al menos 2% de masa muscular desde tu primera evaluacion.');
