import { useQuery } from '@tanstack/react-query';
import { useInject } from '@/lib/di/hooks/useInject';
import { LEAGUE_SERVICE_TOKEN } from '@/lib/di/tokens';
import { enhanceQueryResult } from '@/lib/di/hooks/useReactQueryWithApiError';
import { LeagueScheduleViewModel, LeagueScheduleRaceViewModel } from '@/lib/view-models/LeagueScheduleViewModel';
import type { RaceDTO } from '@/lib/types/generated/RaceDTO';
import { DateDisplay } from '@/lib/display-objects/DateDisplay';

function mapRaceDtoToViewModel(race: RaceDTO): LeagueScheduleRaceViewModel {
  const scheduledAt = race.date ? new Date(race.date) : new Date(0);
  const now = new Date();
  const isPast = scheduledAt.getTime() < now.getTime();

  return {
    id: race.id,
    name: race.name,
    scheduledAt,
    formattedDate: DateDisplay.formatShort(scheduledAt),
    formattedTime: DateDisplay.formatTime(scheduledAt),
    isPast,
    isUpcoming: !isPast,
    status: isPast ? 'completed' : 'scheduled',
    track: undefined,
    car: undefined,
    sessionType: undefined,
    isRegistered: undefined,
  };
}

export function useLeagueSchedule(leagueId: string) {
  const leagueService = useInject(LEAGUE_SERVICE_TOKEN);

  const queryResult = useQuery({
    queryKey: ['leagueSchedule', leagueId],
    queryFn: async (): Promise<LeagueScheduleViewModel> => {
      const result = await leagueService.getLeagueSchedule(leagueId);
      if (result.isErr()) {
        throw new Error(result.getError().message);
      }
      const dto = result.unwrap();
      const races = dto.races.map(mapRaceDtoToViewModel);
      return new LeagueScheduleViewModel(races);
    },
    enabled: !!leagueId,
  });

  return enhanceQueryResult(queryResult);
}
