import { useMutation, UseMutationOptions } from '@tanstack/react-query';
import { useInject } from '@/lib/di/hooks/useInject';
import { RACE_SERVICE_TOKEN } from '@/lib/di/tokens';
import { ApiError } from '@/lib/api/base/ApiError';

interface WithdrawFromRaceParams {
  raceId: string;
  driverId: string;
}

export function useWithdrawFromRace(
  options?: Omit<UseMutationOptions<void, ApiError, WithdrawFromRaceParams>, 'mutationFn'>
) {
  const raceService = useInject(RACE_SERVICE_TOKEN);

  return useMutation<void, ApiError, WithdrawFromRaceParams>({
    mutationFn: async (params) => {
      const result = await raceService.withdrawFromRace(params.raceId, params.driverId);
      if (result.isErr()) {
        const error = result.getError();
        throw new ApiError(error.message, 'SERVER_ERROR', { timestamp: new Date().toISOString() });
      }
    },
    ...options,
  });
}
