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 RegisterForRaceParams {
  raceId: string;
  leagueId: string;
  driverId: string;
}

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

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