-- cuenta_mesa: agregar slug, telefono y metodos de pago del negocio
-- (para que la pagina de la cuenta del cliente sea autosuficiente).
drop function if exists public.cuenta_mesa(uuid);
create function public.cuenta_mesa(p_cuenta_id uuid)
returns table(
  id uuid, mesa text, estado text,
  restaurante_nombre text, restaurante_slug text, restaurante_color text, restaurante_telefono text,
  tasa_bs numeric, total_usd numeric, metodo_pago text, metodos_pago jsonb, pedidos jsonb
)
language sql stable security definer set search_path to 'public'
as $$
  select c.id, c.mesa, c.estado,
         r.nombre, r.slug, r.color_primario, r.telefono,
         r.tasa_bs,
         coalesce((select sum(p.total_usd) from public.pedidos p where p.cuenta_id = c.id), 0),
         c.metodo_pago, r.metodos_pago,
         coalesce((
           select jsonb_agg(jsonb_build_object(
             'codigo', p.codigo, 'estado', p.estado, 'total_usd', p.total_usd,
             'items', coalesce((select jsonb_agg(jsonb_build_object(
                         'nombre', it.nombre, 'cantidad', it.cantidad, 'precio_usd', it.precio_usd, 'nota', it.nota))
                       from public.pedido_items it where it.pedido_id = p.id), '[]'::jsonb)
           ) order by p.recibido_en)
           from public.pedidos p where p.cuenta_id = c.id
         ), '[]'::jsonb)
  from public.cuentas_mesa c
  join public.restaurantes r on r.id = c.restaurante_id
  where c.id = p_cuenta_id;
$$;
grant execute on function public.cuenta_mesa(uuid) to anon, authenticated;
