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

export function useLeagueMembershipMutation() {
  const leagueMembershipService = useInject(LEAGUE_MEMBERSHIP_SERVICE_TOKEN);
  const queryClient = useQueryClient();

  const joinLeagueMutation = useMutation({
    mutationFn: async ({ leagueId, driverId }: { leagueId: string; driverId: string }) => {
      const result = await leagueMembershipService.joinLeague(leagueId, driverId);
      if (result.isErr()) {
        const error = result.getError();
        throw new ApiError(error.message, 'SERVER_ERROR', { timestamp: new Date().toISOString() });
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['leagueMemberships'] });
      queryClient.invalidateQueries({ queryKey: ['allLeagues'] });
    },
  });

  const leaveLeagueMutation = useMutation({
    mutationFn: async ({ leagueId, driverId }: { leagueId: string; driverId: string }) => {
      const result = await leagueMembershipService.leaveLeague(leagueId, driverId);
      if (result.isErr()) {
        const error = result.getError();
        throw new ApiError(error.message, 'SERVER_ERROR', { timestamp: new Date().toISOString() });
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['leagueMemberships'] });
      queryClient.invalidateQueries({ queryKey: ['allLeagues'] });
    },
  });

  return {
    joinLeague: joinLeagueMutation,
    leaveLeague: leaveLeagueMutation,
  };
}
