-- =============================================================================
-- FIX de raiz sobre la reserva "voy a comer alla" (migration 20260722030000):
--
-- 1) crear_pedido creaba una fila en `pagos` para CUALQUIER tipo_entrega
--    distinto de 'mesa', incluyendo 'reserva'. Eso significa que si el cliente
--    pagaba por adelantado (Pago Movil, como probo Gilberto) y LUEGO el mesero
--    lo sentaba, la cuenta_mesa igual sumaba el total de ese pedido en lo que
--    falta por cobrar (cuenta_mesa() suma por cuenta_id sin mirar si ya tiene
--    un pago individual confirmado) -> se le cobraba DOS VECES. Una reserva se
--    paga como cualquier mesa: al final, junto con lo que se agregue despues de
--    sentarse. Se excluye 'reserva' del mismo modo que 'mesa'.
--
-- 2) pedido_seguimiento (la pantalla que ve el cliente en /pedido/:id) no
--    exponia mesa/cuenta_id/personas, asi que no habia forma de decirle "ya
--    tienes mesa asignada" una vez que el mesero lo sienta. Se agregan esas
--    3 columnas (RETURNS TABLE cambia de forma, hace falta DROP primero).
-- =============================================================================

-- --- 1) crear_pedido: reserva tampoco crea `pagos` individual ---------------
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::text, p_direccion_lat double precision DEFAULT NULL::double precision, p_direccion_lng double precision DEFAULT NULL::double precision, p_nota text DEFAULT NULL::text, p_mesa text DEFAULT NULL::text, p_cedula text DEFAULT NULL::text, p_comensal_id uuid DEFAULT NULL::uuid, p_para_llevar boolean DEFAULT false, p_personas int DEFAULT NULL::int)
 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;
  v_comensal_id    uuid := null;
  v_estado         text := 'recibido';
  v_para_llevar    boolean := coalesce(p_para_llevar, false) and p_tipo_entrega = 'mesa';
  v_personas       int := 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','reserva') 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;

  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;

  if p_tipo_entrega = 'reserva' then
    v_personas := greatest(1, coalesce(p_personas, 1));
  end if;

  if p_tipo_entrega in ('delivery','pickup','reserva') 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
    v_estado := 'confirmado';
    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;
    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;
    if p_comensal_id is not null then
      perform 1 from public.comensales_mesa cm where cm.id = p_comensal_id and cm.cuenta_id = v_cuenta_id;
      if not found then raise exception 'La persona no pertenece a esta mesa'; end if;
      v_comensal_id := p_comensal_id;
    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, confirmado_en,
    subtotal_usd, costo_delivery_usd, total_usd, tasa_bs, metodo_pago, nota, cuenta_id, firma,
    mesero_id, mesero_nombre, comensal_id, para_llevar, personas
  ) 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, v_estado, case when v_estado = 'confirmado' then now() else null end,
    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, v_comensal_id, v_para_llevar, v_personas
  ) 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;

  -- Reserva se paga como cualquier mesa: al final, junto con lo que se agregue
  -- despues de sentarse. Sin esto, el pre-pago individual (SeccionPago) se
  -- solapa con el cobro de la cuenta de mesa y el cliente paga dos veces.
  if p_tipo_entrega not in ('mesa','reserva') 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$;

-- --- 2) pedido_seguimiento: agrega mesa/cuenta_id/personas ------------------
-- El return type cambia de forma (3 columnas nuevas): CREATE OR REPLACE no lo
-- permite, hace falta DROP primero (misma leccion que crear_pedido con params).
DROP FUNCTION IF EXISTS public.pedido_seguimiento(uuid);

CREATE OR REPLACE FUNCTION public.pedido_seguimiento(p_pedido_id uuid)
 RETURNS TABLE(codigo text, estado text, tipo_entrega text, total_usd numeric, tasa_bs numeric, restaurante_nombre text, restaurante_telefono text, restaurante_color text, direccion text, direccion_latitud double precision, direccion_longitud double precision, repartidor_latitud double precision, repartidor_longitud double precision, repartidor_ubicacion_en timestamp with time zone, recibido_en timestamp with time zone, confirmado_en timestamp with time zone, listo_en timestamp with time zone, en_camino_en timestamp with time zone, entregado_en timestamp with time zone, tiempo_estimado_min integer, mesa text, cuenta_id uuid, personas int)
 LANGUAGE sql
 STABLE SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
  select p.codigo, p.estado, p.tipo_entrega, p.total_usd, p.tasa_bs,
         r.nombre, r.telefono, r.color_primario,
         p.direccion, p.direccion_latitud, p.direccion_longitud,
         rep.ultima_latitud, rep.ultima_longitud, rep.ultima_ubicacion_en,
         p.recibido_en, p.confirmado_en, p.listo_en, p.en_camino_en, p.entregado_en,
         p.tiempo_estimado_min, p.mesa, p.cuenta_id, p.personas
    from public.pedidos p
    join public.restaurantes r on r.id = p.restaurante_id
    left join public.repartidores rep on rep.id = p.repartidor_id
   where p.id = p_pedido_id;
$function$;
