-- ============================================================
-- Gustito Express — El dueño gestiona sus repartidores desde el panel.
-- Listar la flota del restaurante (con nombre/telefono, que viven en perfiles).
-- La CREACION del repartidor va por Edge Function (requiere admin auth).
-- ============================================================
create or replace function public.mis_repartidores()
returns table (
  repartidor_id uuid,
  nombre        text,
  telefono      text,
  vehiculo      text,
  estado        text,
  creado_en     timestamptz
)
language sql stable security definer set search_path = public
as $$
  select r.id, p.nombre, p.telefono, r.vehiculo, r.estado, r.creado_en
  from public.repartidores r
  join public.perfiles p on p.id = r.perfil_id
  where r.restaurante_id = fn_mi_restaurante()
    and (fn_es_staff_de(r.restaurante_id) or fn_es_admin())
  order by r.creado_en desc;
$$;
grant execute on function public.mis_repartidores() to authenticated;
revoke execute on function public.mis_repartidores() from public;
