-- El "Desde $X" del directorio calculaba min(precio_usd), pero los productos por tamano
-- tienen base 0 (el precio vive en la opcion) -> daba "Desde $0". Ahora usa el precio
-- EFECTIVO: base + la opcion obligatoria mas barata (Cantidad c/u o Elige 1).
create or replace function public.directorio()
returns table(
  slug text, nombre text, descripcion text, logo_url text, portada_url text, rubro text,
  rubros text[], estado_ve text, municipio text, latitud double precision, longitud double precision,
  color_primario text, hace_delivery boolean, costo_delivery_usd numeric, tasa_bs numeric,
  abierto boolean, precio_desde numeric
)
language sql
stable
security definer
set search_path to 'public'
as $function$
  select r.slug, r.nombre, r.descripcion, r.logo_url, r.portada_url,
         r.rubro, r.rubros, r.estado_ve, r.municipio,
         r.latitud, r.longitud,
         r.color_primario, r.hace_delivery, r.costo_delivery_usd,
         r.tasa_bs, r.abierto,
         (
           select min(pmin.efectivo) from (
             select p.precio_usd + coalesce((
               select sum(gc.cheapest) from (
                 select (select min((o->>'precio_extra')::numeric) from jsonb_array_elements(g->'opciones') o) cheapest
                 from jsonb_array_elements(coalesce(p.opciones, '[]'::jsonb)) g
                 where coalesce((g->>'obligatorio')::boolean, false)
                   and (g->>'tipo') in ('cantidad', 'single')
               ) gc
             ), 0) as efectivo
             from public.productos p
             where p.restaurante_id = r.id and p.disponible
           ) pmin
         )
  from public.restaurantes r
  where r.publicado and r.activo and r.en_directorio
  order by r.abierto desc, r.nombre;
$function$;
