-- ============================================================
-- Gustito Express — MODO MESERO.
--
-- 1) Pedidos y cuentas de mesa registran QUIEN atiende. La identidad
--    sale de auth.uid() DENTRO de crear_pedido (server-side): aunque la
--    app tenga un bug, un mesero no puede firmar como otro.
-- 2) Un mesero atiende varias mesas a la vez sin candado extra: el
--    indice unico uq_cuenta_mesa_activa (una cuenta activa por mesa)
--    sigue siendo la garantia anti-cruce y NO se toca.
-- 3) Candados de rol: 'staff' (mesero) queda operativo (POS, mesas,
--    cocina, pedidos, cobrar) pero pierde poderes de dueño que hoy
--    tenia por accidente: editar negocio/menu/precios, administrar
--    flota, caja, CRM y cerrar_negocio.
-- ============================================================

-- ---- Helper: dueño (mas estricto que fn_es_staff_de) ----
create or replace function public.fn_es_dueno_de(p_restaurante uuid)
returns boolean language sql stable security definer set search_path = public as $$
  select exists (
    select 1 from public.perfiles
    where id = auth.uid()
      and restaurante_id = p_restaurante
      and rol = 'dueno'
  );
$$;

-- ---- Columnas: quien atiende ----
alter table public.pedidos      add column if not exists mesero_id uuid references public.perfiles(id) on delete set null;
alter table public.pedidos      add column if not exists mesero_nombre text;
alter table public.cuentas_mesa add column if not exists mesero_id uuid references public.perfiles(id) on delete set null;
alter table public.cuentas_mesa add column if not exists mesero_nombre text;

-- ---- crear_pedido: estampa la identidad del que atiende ----
-- Cambio quirurgico sobre el cuerpo VIVO (2026-07-17): solo se agregan
-- v_mesero_* y su estampado; precios, anti-duplicado y numeracion intactos.
create or replace function public.crear_pedido(
  p_restaurante_id uuid, p_cliente_nombre text, p_cliente_telefono text, p_tipo_entrega text,
  p_metodo_pago text, p_items jsonb, p_direccion text default null,
  p_direccion_lat double precision default null, p_direccion_lng double precision default null,
  p_nota text default null, p_mesa text default null, p_cedula text default null
)
returns table(pedido_id uuid, codigo text, cuenta_id uuid)
language plpgsql security definer set search_path to 'public'
as $function$
declare
  v_rest           public.restaurantes%rowtype;
  v_item           jsonb;
  v_prod           public.productos%rowtype;
  v_cant           int;
  v_extra          numeric(10,2) := 0;
  v_subtotal       numeric(10,2) := 0;
  v_costo_delivery numeric(10,2) := 0;
  v_pedido_id      uuid;
  v_codigo         text;
  v_num            int;
  v_cuenta_id      uuid := null;
  v_firma          text := null;
  v_dup_id         uuid;
  v_dup_codigo     text;
  v_dup_cuenta     uuid;
  v_mesero_id      uuid := null;
  v_mesero_nombre  text := null;
begin
  select * into v_rest from public.restaurantes where id = p_restaurante_id;
  if not found or not v_rest.activo or not v_rest.publicado then
    raise exception 'Restaurante no disponible';
  end if;
  if not v_rest.abierto then
    raise exception 'El restaurante esta cerrado en este momento';
  end if;
  if p_tipo_entrega not in ('delivery','pickup','mesa') then
    raise exception 'Tipo de entrega invalido';
  end if;
  if p_metodo_pago not in ('pago_movil','efectivo','transferencia','zelle','punto_venta') then
    raise exception 'Metodo de pago invalido';
  end if;
  if jsonb_array_length(coalesce(p_items, '[]'::jsonb)) = 0 then
    raise exception 'El carrito esta vacio';
  end if;

  -- Quien atiende: SOLO si el llamador es personal DE ESTE restaurante.
  -- Un cliente (anon/comensal) deja los campos en null; un mesero de otro
  -- negocio pidiendo aqui cuenta como cliente normal.
  if auth.uid() is not null then
    select pf.id, coalesce(nullif(trim(pf.nombre), ''), 'Mesero')
      into v_mesero_id, v_mesero_nombre
      from public.perfiles pf
     where pf.id = auth.uid()
       and pf.restaurante_id = p_restaurante_id
       and pf.rol in ('dueno','staff');
  end if;

  if p_tipo_entrega = 'delivery' then
    v_costo_delivery := coalesce(v_rest.costo_delivery_usd, 0);
    if coalesce(length(trim(p_direccion)), 0) < 4 then
      raise exception 'Para delivery necesitas indicar la direccion';
    end if;
  end if;

  -- Anti-duplicado (idempotente) para delivery/pickup.
  if p_tipo_entrega in ('delivery','pickup') then
    v_firma := md5(coalesce(lower(trim(p_cliente_telefono)), '') || '|' || coalesce(p_items::text, ''));
    select p.id, p.codigo, p.cuenta_id into v_dup_id, v_dup_codigo, v_dup_cuenta
      from public.pedidos p
     where p.restaurante_id = p_restaurante_id
       and p.firma = v_firma
       and p.recibido_en > now() - interval '3 minutes'
     order by p.recibido_en desc
     limit 1;
    if found then
      return query select v_dup_id, v_dup_codigo, v_dup_cuenta;
      return;
    end if;
  end if;

  if p_tipo_entrega = 'mesa' then
    if coalesce(nullif(p_mesa, ''), '') = '' then
      raise exception 'Falta el numero de mesa';
    end if;
    insert into public.cuentas_mesa (restaurante_id, mesa, mesero_id, mesero_nombre)
      values (p_restaurante_id, p_mesa, v_mesero_id, v_mesero_nombre)
      on conflict (restaurante_id, mesa) where (estado <> 'cerrada') do nothing;
    select cm.id into v_cuenta_id from public.cuentas_mesa cm
      where cm.restaurante_id = p_restaurante_id and cm.mesa = p_mesa and cm.estado <> 'cerrada'
      limit 1;
    -- Cuenta abierta por QR (sin mesero): queda a nombre del primero del
    -- personal que la toque. Si ya tiene mesero, NO se pisa.
    if v_mesero_id is not null and v_cuenta_id is not null then
      update public.cuentas_mesa
         set mesero_id = v_mesero_id, mesero_nombre = v_mesero_nombre
       where id = v_cuenta_id and mesero_id is null;
    end if;
  end if;

  update public.restaurantes set contador_pedidos = contador_pedidos + 1
   where id = p_restaurante_id
   returning contador_pedidos into v_num;
  v_codigo := coalesce(nullif(v_rest.prefijo, ''), 'GX') || '-' || lpad(v_num::text, 4, '0');

  insert into public.pedidos (
    restaurante_id, codigo, cliente_nombre, cliente_telefono, cliente_cedula, tipo_entrega, mesa,
    direccion, direccion_latitud, direccion_longitud, estado,
    subtotal_usd, costo_delivery_usd, total_usd, tasa_bs, metodo_pago, nota, cuenta_id, firma,
    mesero_id, mesero_nombre
  ) values (
    p_restaurante_id, v_codigo, p_cliente_nombre, p_cliente_telefono, nullif(p_cedula, ''), p_tipo_entrega, nullif(p_mesa, ''),
    p_direccion, p_direccion_lat, p_direccion_lng, 'recibido',
    0, v_costo_delivery, 0, v_rest.tasa_bs, p_metodo_pago, p_nota, v_cuenta_id, v_firma,
    v_mesero_id, v_mesero_nombre
  ) returning id into v_pedido_id;

  for v_item in select * from jsonb_array_elements(p_items)
  loop
    v_cant := greatest(1, coalesce((v_item->>'cantidad')::int, 1));
    select * into v_prod from public.productos
      where id = (v_item->>'producto_id')::uuid
        and restaurante_id = p_restaurante_id;
    if not found then
      raise exception 'Un producto no pertenece a este restaurante';
    end if;
    if not v_prod.disponible then
      raise exception 'Producto agotado: %', v_prod.nombre;
    end if;
    select coalesce(sum((op->>'precio_extra')::numeric), 0) into v_extra
      from jsonb_array_elements(coalesce(v_prod.opciones, '[]'::jsonb)) as grupo,
           jsonb_array_elements(coalesce(grupo->'opciones', '[]'::jsonb)) as op
     where jsonb_exists(coalesce(v_item->'opciones', '[]'::jsonb), op->>'nombre');
    insert into public.pedido_items (pedido_id, producto_id, nombre, precio_usd, cantidad, nota)
      values (v_pedido_id, v_prod.id, v_prod.nombre, v_prod.precio_usd + v_extra, v_cant, nullif(v_item->>'nota', ''));
    v_subtotal := v_subtotal + (v_prod.precio_usd + v_extra) * v_cant;
  end loop;

  update public.pedidos
     set subtotal_usd = v_subtotal,
         total_usd    = v_subtotal + v_costo_delivery
   where id = v_pedido_id;

  if p_tipo_entrega <> 'mesa' then
    insert into public.pagos (pedido_id, metodo, monto_usd, estado)
      values (v_pedido_id, p_metodo_pago, v_subtotal + v_costo_delivery, 'pendiente');
  end if;

  return query select v_pedido_id, v_codigo, v_cuenta_id;
end;
$function$;

-- ---- cuenta_mesa_activa: + quien atiende (la ve el cliente en su mesa) ----
-- RETURNS TABLE cambia -> DROP previo obligatorio.
drop function if exists public.cuenta_mesa_activa(uuid, text);
create function public.cuenta_mesa_activa(p_restaurante_id uuid, p_mesa text)
returns table(id uuid, mesa text, estado text, total_usd numeric, mesero_nombre text)
language sql stable security definer set search_path to 'public'
as $$
  select c.id, c.mesa, c.estado,
         coalesce((select sum(p.total_usd) from public.pedidos p where p.cuenta_id = c.id), 0),
         c.mesero_nombre
  from public.cuentas_mesa c
  where c.restaurante_id = p_restaurante_id
    and c.mesa = p_mesa
    and c.estado <> 'cerrada'
  limit 1;
$$;
grant execute on function public.cuenta_mesa_activa(uuid, text) to anon, authenticated;

-- ---- cuenta_mesa (pantalla del cliente): + "Te atiende" ----
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, promedio_min integer, pedidos jsonb, mesero_nombre text
)
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(r.sala_promedio_min, 10),
         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),
         c.mesero_nombre
  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;

-- ---- mis_cuentas_mesa (panel): + quien atiende cada mesa ----
drop function if exists public.mis_cuentas_mesa(uuid);
create function public.mis_cuentas_mesa(p_restaurante_id uuid)
returns table(
  id uuid, mesa text, estado text, total_usd numeric, tasa_bs numeric,
  abierta_en timestamptz, pago_solicitado_en timestamptz, metodo_pago text,
  referencia text, comprobante_url text, n_pedidos integer,
  mesero_id uuid, mesero_nombre text
)
language sql stable security definer set search_path to 'public'
as $$
  select c.id, c.mesa, c.estado,
    coalesce((select sum(p.total_usd) from public.pedidos p where p.cuenta_id = c.id), 0),
    r.tasa_bs, c.abierta_en, c.pago_solicitado_en, c.metodo_pago, c.referencia, c.comprobante_url,
    (select count(*)::int from public.pedidos p where p.cuenta_id = c.id),
    c.mesero_id, c.mesero_nombre
  from public.cuentas_mesa c
  join public.restaurantes r on r.id = c.restaurante_id
  where c.restaurante_id = p_restaurante_id
    and c.estado <> 'cerrada'
    and (fn_es_staff_de(c.restaurante_id) or fn_es_admin())
  order by c.abierta_en;
$$;
grant execute on function public.mis_cuentas_mesa(uuid) to anon, authenticated;

-- ---- mis_meseros: el dueño lista su equipo de sala ----
create or replace function public.mis_meseros()
returns table(mesero_id uuid, nombre text, telefono text, correo text, creado_en timestamptz)
language sql stable security definer set search_path to 'public'
as $$
  select pf.id, pf.nombre, pf.telefono, u.email::text, pf.creado_en
  from public.perfiles pf
  join auth.users u on u.id = pf.id
  where pf.restaurante_id = fn_mi_restaurante()
    and pf.rol = 'staff'
    and (fn_es_dueno_de(pf.restaurante_id) or fn_es_admin())
  order by pf.creado_en desc;
$$;
grant execute on function public.mis_meseros() to authenticated;

-- ---- cerrar_negocio: SOLO dueño (antes bastaba ser staff) ----
create or replace function public.cerrar_negocio()
returns void
language plpgsql security definer set search_path to 'public'
as $function$
declare v_rest uuid := fn_mi_restaurante();
begin
  if v_rest is null or not (fn_es_dueno_de(v_rest) or fn_es_admin()) then
    raise exception 'Sin permiso';
  end if;
  update public.restaurantes set abierto = false where id = v_rest;
  -- ocultar datos personales (se conserva el pedido y sus totales)
  update public.pedidos
     set cliente_nombre     = 'Cliente',
         cliente_telefono   = '',
         cliente_cedula     = null,
         direccion          = null,
         direccion_latitud  = null,
         direccion_longitud = null,
         nota               = null
   where restaurante_id = v_rest
     and cliente_telefono <> '';            -- no re-procesar pedidos ya ocultados
  update public.pagos
     set referencia = null, comprobante_url = null
   where pedido_id in (select id from public.pedidos where restaurante_id = v_rest);
  update public.repartidores set estado = 'disponible' where restaurante_id = v_rest and estado = 'ocupado';
end;
$function$;

-- ---- Candados de rol: lo administrativo vuelve a ser SOLO del dueño ----

-- Negocio (abrir/cerrar, config, tasa, mesas): dueño.
drop policy if exists restaurantes_staff_update on public.restaurantes;
create policy restaurantes_dueno_update on public.restaurantes
  for update to authenticated
  using (fn_es_dueno_de(id) or fn_es_admin())
  with check (fn_es_dueno_de(id) or fn_es_admin());

-- Menu: dueño escribe; la lectura publica no cambia.
drop policy if exists categorias_staff_escribe on public.categorias;
create policy categorias_dueno_escribe on public.categorias
  for all to authenticated
  using (fn_es_dueno_de(restaurante_id) or fn_es_admin())
  with check (fn_es_dueno_de(restaurante_id) or fn_es_admin());

drop policy if exists productos_staff_escribe on public.productos;
create policy productos_dueno_escribe on public.productos
  for all to authenticated
  using (fn_es_dueno_de(restaurante_id) or fn_es_admin())
  with check (fn_es_dueno_de(restaurante_id) or fn_es_admin());

-- Flota: el dueño la administra; el staff solo la VE (selector del POS).
drop policy if exists repartidores_staff on public.repartidores;
create policy repartidores_dueno_admin on public.repartidores
  for all to authenticated
  using (fn_es_dueno_de(restaurante_id) or fn_es_admin())
  with check (fn_es_dueno_de(restaurante_id) or fn_es_admin());
create policy repartidores_staff_select on public.repartidores
  for select to authenticated
  using (fn_es_staff_de(restaurante_id) or fn_es_admin());

-- Caja: dueño (antes: CUALQUIER perfil del restaurante, incluso repartidor).
drop policy if exists gastos_caja_select on public.gastos_caja;
drop policy if exists gastos_caja_insert on public.gastos_caja;
drop policy if exists gastos_caja_delete on public.gastos_caja;
create policy gastos_caja_dueno on public.gastos_caja
  for all to authenticated
  using (fn_es_dueno_de(restaurante_id) or fn_es_admin())
  with check (fn_es_dueno_de(restaurante_id) or fn_es_admin());

-- CRM de clientes: dueño (mismo hueco del patron anterior).
drop policy if exists clientes_select on public.clientes;
create policy clientes_dueno_select on public.clientes
  for select to authenticated
  using (fn_es_dueno_de(restaurante_id) or fn_es_admin());
