-- ============================================================
-- Gustito Express — Tiempo estimado de preparacion por pedido.
-- El encargado lo fija al aceptar el pedido; el cliente lo ve en su seguimiento.
-- ============================================================
alter table public.pedidos add column if not exists tiempo_estimado_min int;

-- Aceptar un pedido: fija el tiempo estimado y, si sigue en 'recibido', lo pasa a 'confirmado'.
create or replace function public.aceptar_pedido(p_pedido_id uuid, p_min int)
returns text
language plpgsql
security definer
set search_path to 'public'
as $$
declare
  v_ped public.pedidos%rowtype;
begin
  select * into v_ped from public.pedidos where id = p_pedido_id;
  if not found then raise exception 'Pedido no existe'; end if;
  if not (fn_es_staff_de(v_ped.restaurante_id) or fn_es_admin()) then
    raise exception 'Sin permiso para este pedido';
  end if;
  if p_min is not null and (p_min < 0 or p_min > 600) then
    raise exception 'Tiempo estimado invalido';
  end if;
  update public.pedidos
     set tiempo_estimado_min = p_min,
         estado        = case when estado = 'recibido' then 'confirmado' else estado end,
         confirmado_en = case when estado = 'recibido' then now() else confirmado_en end
   where id = p_pedido_id;
  return 'ok';
end;
$$;
grant execute on function public.aceptar_pedido(uuid, int) to authenticated;

-- Recrear pedido_seguimiento incluyendo el tiempo estimado (cambia el tipo de retorno -> drop+create).
drop function if exists public.pedido_seguimiento(uuid);
create 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,
  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 int
)
language sql
stable security definer
set search_path to 'public'
as $$
  select p.codigo, p.estado, p.tipo_entrega, p.total_usd, p.tasa_bs,
         r.nombre, r.telefono,
         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
    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;
$$;
grant execute on function public.pedido_seguimiento(uuid) to anon, authenticated;
