-- Permite REASIGNAR un pedido a otro repartidor (por si el asignado se accidenta o no puede):
-- al cambiar de repartidor, libera al anterior (queda 'disponible' si no le quedan pedidos activos).
create or replace function public.asignar_repartidor(p_pedido_id uuid, p_repartidor_id uuid)
returns void
language plpgsql
security definer
set search_path to 'public'
as $function$
declare
  v_rest uuid;
  v_rep_rest uuid;
  v_old uuid;
begin
  select restaurante_id, repartidor_id into v_rest, v_old 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_rest) or fn_es_admin()) then raise exception 'Sin permiso'; end if;

  select restaurante_id into v_rep_rest from public.repartidores where id = p_repartidor_id;
  if not found or v_rep_rest <> v_rest then raise exception 'Repartidor invalido'; end if;

  update public.pedidos set repartidor_id = p_repartidor_id where id = p_pedido_id;
  update public.repartidores set estado = 'ocupado' where id = p_repartidor_id;

  -- Reasignacion: liberar al repartidor anterior si ya no tiene pedidos activos.
  if v_old is not null and v_old <> p_repartidor_id then
    update public.repartidores set estado = 'disponible'
     where id = v_old
       and not exists (
         select 1 from public.pedidos
          where repartidor_id = v_old and estado in ('listo', 'en_camino')
       );
  end if;
end;
$function$;
