import type { IRaceRepository } from '../../domain/repositories/IRaceRepository';
import type { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
import type { RacesPageResultDTO } from '@core/racing/application/presenters/IRacesPagePresenter';
import type { AsyncUseCase } from '@core/shared/application/AsyncUseCase';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

export class GetRacesPageDataUseCase implements AsyncUseCase<void, RacesPageResultDTO, 'NO_ERROR'> {
  constructor(
    private readonly raceRepository: IRaceRepository,
    private readonly leagueRepository: ILeagueRepository,
  ) {}

  async execute(): Promise<Result<RacesPageResultDTO, ApplicationErrorCode<'NO_ERROR'>>> {
    const [allRaces, allLeagues] = await Promise.all([
      this.raceRepository.findAll(),
      this.leagueRepository.findAll(),
    ]);

    const leagueMap = new Map(allLeagues.map(l => [l.id, l.name]));

    const races = allRaces
      .sort((a, b) => a.scheduledAt.getTime() - b.scheduledAt.getTime())
      .map(race => ({
        id: race.id,
        track: race.track,
        car: race.car,
        scheduledAt: race.scheduledAt.toISOString(),
        status: race.status,
        leagueId: race.leagueId,
        leagueName: leagueMap.get(race.leagueId) ?? 'Unknown League',
        strengthOfField: race.strengthOfField,
        isUpcoming: race.isUpcoming(),
        isLive: race.isLive(),
        isPast: race.isPast(),
      }));

    const dto: RacesPageResultDTO = {
      races,
    };

    return Result.ok(dto);
  }
}