-- ETAPA 2.B del cerebrito:
--  (1) fn_local_en_linea: la tienda (anon) pregunta si el sistema local del
--      negocio respira, para el AVISO SUAVE del QR de mesa (no bloquea nada;
--      solo devuelve un estado, cero datos sensibles).
--  (2) fn_cerebritos_tablero: el tablero central del fundador/admin (que
--      laptop esta viva, su version y su carga). Para otros roles devuelve
--      vacio (sin fuga).

create or replace function public.fn_local_en_linea(p_restaurante uuid)
 returns text
 language sql
 stable
 security definer
 set search_path to 'public'
as $function$
  select case
    when c.restaurante_id is null then 'sin_cerebrito'
    when c.visto_en > now() - interval '3 minutes' then 'en_linea'
    else 'sin_conexion'
  end
  from (select 1) unidad
  left join public.cerebritos c on c.restaurante_id = p_restaurante;
$function$;

create or replace function public.fn_cerebritos_tablero()
 returns table (restaurante text, visto_en timestamptz, version text, detalle jsonb)
 language sql
 stable
 security definer
 set search_path to 'public'
as $function$
  select r.nombre, c.visto_en, c.version, c.detalle
    from public.cerebritos c
    join public.restaurantes r on r.id = c.restaurante_id
   where exists (
           select 1 from public.perfiles p
            where p.id = auth.uid() and (p.es_fundador or p.rol = 'admin')
         )
   order by c.visto_en desc;
$function$;

revoke all on function public.fn_local_en_linea(uuid) from public;
revoke all on function public.fn_cerebritos_tablero() from public, anon;
grant execute on function public.fn_local_en_linea(uuid) to anon, authenticated;
grant execute on function public.fn_cerebritos_tablero() to authenticated;
