-- ============================================================
-- Gustito Express — La vitrina: directorio publico de negocios.
-- La gente busca que comer (rubro), filtra por estado/municipio, ve los cercanos
-- y compara. Cada negocio elige si aparece (en_directorio).
-- ============================================================
alter table public.restaurantes
  add column if not exists rubro         text,
  add column if not exists estado_ve     text,
  add column if not exists municipio     text,
  add column if not exists en_directorio boolean not null default true;

create index if not exists idx_restaurantes_directorio
  on public.restaurantes (estado_ve, rubro)
  where publicado and activo and en_directorio;

-- Directorio: negocios publicados, activos y opt-in. Solo campos seguros para
-- mostrar en la vitrina, mas el precio "desde" (producto mas barato) para comparar.
create or replace function public.directorio()
returns table (
  slug               text,
  nombre             text,
  descripcion        text,
  logo_url           text,
  portada_url        text,
  rubro              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 = public
as $$
  select r.slug, r.nombre, r.descripcion, r.logo_url, r.portada_url,
         r.rubro, 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(p.precio_usd) from public.productos p
           where p.restaurante_id = r.id and p.disponible)
  from public.restaurantes r
  where r.publicado and r.activo and r.en_directorio
  order by r.abierto desc, r.nombre;
$$;
grant execute on function public.directorio() to anon, authenticated;
