-- El "Desde $X" del directorio ahora se calcula sobre la COMIDA (categorias tipo comida),
-- no sobre bebidas/adicionales. Asi refleja el plato mas barato (ej. empanada), no el
-- refresco mas economico. Si el negocio no tuviera comida, cae de vuelta a todo el menu.
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,
         (
           with efectivos as (
             select c.grupo,
                    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
             left join public.categorias c on c.id = p.categoria_id
             where p.restaurante_id = r.id and p.disponible
           )
           select coalesce(
             (select min(efectivo) from efectivos where grupo = 'comida'),
             (select min(efectivo) from efectivos)
           )
         )
  from public.restaurantes r
  where r.publicado and r.activo and r.en_directorio
  order by r.abierto desc, r.nombre;
$function$;
