-- El repartidor no veia QUE lleva: las RPC mis_entregas_activas y
-- entregas_disponibles devuelven codigo, cliente, direccion y total, pero
-- nunca los productos del pedido. Sin eso no puede verificar la bolsa.
--
-- Esta funcion expone los items SOLO de las entregas que el repartidor tiene
-- derecho a ver: las asignadas a el (en cualquier estado, para que el historial
-- tambien muestre el detalle) o las disponibles (delivery 'listo' sin asignar)
-- en un restaurante donde pertenece a la flota. Un id que no cumpla no devuelve
-- filas, asi que no hay fuga de pedidos ajenos.
create or replace function public.items_entregas_repartidor(p_ids uuid[])
returns table(pedido_id uuid, nombre text, cantidad integer, nota text)
language sql
stable
security definer
set search_path to 'public'
as $function$
  select pi.pedido_id, pi.nombre, pi.cantidad, pi.nota
  from public.pedido_items pi
  join public.pedidos p on p.id = pi.pedido_id
  where pi.pedido_id = any(p_ids)
    and (
      exists (
        select 1 from public.repartidores r
        where r.id = p.repartidor_id and r.perfil_id = auth.uid()
      )
      or (
        p.tipo_entrega = 'delivery'
        and p.estado = 'listo'
        and p.repartidor_id is null
        and p.restaurante_id in (
          select restaurante_id from public.repartidores where perfil_id = auth.uid()
        )
      )
    )
  order by pi.pedido_id, lower(pi.nombre);
$function$;

revoke all on function public.items_entregas_repartidor(uuid[]) from public;
grant execute on function public.items_entregas_repartidor(uuid[]) to authenticated;
