-- ============================================================
-- Gustito Express — un negocio puede vender de varios rubros.
-- Antes era 1 solo (columna 'rubro'); ahora una lista ('rubros').
-- Se conserva 'rubro' como principal (rubros[1]) por compatibilidad.
-- ============================================================
alter table public.restaurantes
  add column if not exists rubros text[] not null default '{}';

-- Backfill: el rubro unico existente pasa a ser el primero de la lista.
update public.restaurantes
   set rubros = array[rubro]
 where rubro is not null and rubro <> '' and (rubros is null or rubros = '{}');

-- El directorio expone la lista completa de rubros (y conserva 'rubro' principal).
drop function if exists public.directorio();
create 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 = public
as $$
  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(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;
