-- ============================================================
-- Gustito Express — Al registrarse un usuario, crear su perfil (rol comensal por defecto).
-- Los roles dueno/staff/repartidor se asignan luego (panel admin o seed).
-- ============================================================
create or replace function public.handle_new_user()
returns trigger language plpgsql security definer set search_path = public
as $$
begin
  insert into public.perfiles (id, rol, nombre, telefono)
  values (
    new.id,
    'comensal',
    new.raw_user_meta_data->>'nombre',
    new.raw_user_meta_data->>'telefono'
  )
  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();
