import type { GetAllRacesResult } from '@core/racing/application/use-cases/GetAllRacesUseCase';
import type { AllRacesPageDTO } from '../dtos/AllRacesPageDTO';

export type GetAllRacesResponseModel = AllRacesPageDTO;

export class GetAllRacesPresenter {
  private model: GetAllRacesResponseModel | null = null;

  present(result: GetAllRacesResult): void {
    const leagueMap = new Map<string, string>();
    const uniqueLeagues = new Map<string, { id: string; name: string }>();

    for (const league of result.leagues) {
      const id = league.id.toString();
      const name = league.name.toString();
      leagueMap.set(id, name);
      uniqueLeagues.set(id, { id, name });
    }

    this.model = {
      races: result.races.map(race => ({
        id: race.id,
        track: race.track,
        car: race.car,
        scheduledAt: race.scheduledAt.toISOString(),
        status: race.status.toString(),
        leagueId: race.leagueId,
        leagueName: leagueMap.get(race.leagueId) ?? 'Unknown League',
        strengthOfField:
          typeof race.strengthOfField === 'number'
            ? race.strengthOfField
            : race.strengthOfField?.toNumber() ?? null,
      })),
      filters: {
        statuses: [
          { value: 'all', label: 'All' },
          { value: 'scheduled', label: 'Scheduled' },
          { value: 'running', label: 'Running' },
          { value: 'completed', label: 'Completed' },
          { value: 'cancelled', label: 'Cancelled' },
        ],
        leagues: Array.from(uniqueLeagues.values()),
      },
    };
  }

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

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

    return this.model;
  }

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