import type { GetRacesPageDataResult } from '@core/racing/application/use-cases/GetRacesPageDataUseCase';
import type { RacesPageDataDTO } from '../dtos/RacesPageDataDTO';
import type { RacesPageDataRaceDTO } from '../dtos/RacesPageDataRaceDTO';

export type GetRacesPageDataResponseModel = RacesPageDataDTO;

export class RacesPageDataPresenter {
  private model: GetRacesPageDataResponseModel | null = null;

  reset(): void {
    this.model = null;
  }

  present(result: GetRacesPageDataResult): void {
    const races: RacesPageDataRaceDTO[] = result.races.map(({ race, leagueName }) => ({
      id: race.id,
      track: race.track,
      car: race.car,
      scheduledAt: race.scheduledAt.toISOString(),
      status: race.status.toString(),
      leagueId: race.leagueId,
      leagueName,
      strengthOfField: race.strengthOfField?.toNumber() ?? null,
      isUpcoming: race.scheduledAt > new Date(),
      isLive: race.status.isRunning(),
      isPast: race.scheduledAt < new Date() && race.status.isCompleted(),
    }));

    this.model = { races } as RacesPageDataDTO;
  }

  getResponseModel(): GetRacesPageDataResponseModel | null {
    return this.model;
  }

  get responseModel(): GetRacesPageDataResponseModel {
    if (!this.model) {
      throw new Error('Presenter not presented');
    }

    return this.model;
  }

  get viewModel(): GetRacesPageDataResponseModel {
    return this.responseModel;
  }
}