import type { Logger } from '@core/shared/domain/Logger';
import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { League } from '../../domain/entities/League';
import type { Race } from '../../domain/entities/Race';
import { LeagueRepository } from '../../domain/repositories/LeagueRepository';
import { RaceRepository } from '../../domain/repositories/RaceRepository';

export interface GetRacesPageDataInput {
  leagueId: string;
}

export type GetRacesPageRaceItem = {
  race: Race;
  leagueName: string;
};

export type GetRacesPageDataResult = {
  leagueId: string;
  races: GetRacesPageRaceItem[];
};

export type GetRacesPageDataErrorCode = 'REPOSITORY_ERROR';

export class GetRacesPageDataUseCase {
  constructor(
    private readonly raceRepository: RaceRepository,
    private readonly leagueRepository: LeagueRepository,
    private readonly logger: Logger,
  ) {}

  async execute(
    input: GetRacesPageDataInput,
  ): Promise<Result<GetRacesPageDataResult, ApplicationErrorCode<GetRacesPageDataErrorCode, { message: string }>>> {
    this.logger.debug('GetRacesPageDataUseCase:execute', { input });

    try {
      const [allRaces, allLeagues] = await Promise.all([
        this.raceRepository.findAll(),
        this.leagueRepository.findAll(),
      ]);

      const leagueMap = new Map(
        allLeagues.map((league: League) => [league.id.toString(), league.name.toString()]),
      );

      const filteredRaces = input.leagueId
        ? allRaces.filter((race: Race) => race.leagueId === input.leagueId)
        : allRaces;
      
      filteredRaces.sort((a: Race, b: Race) => a.scheduledAt.getTime() - b.scheduledAt.getTime());

      const races: GetRacesPageRaceItem[] = filteredRaces.map((race: Race) => ({
        race,
        leagueName: leagueMap.get(race.leagueId) ?? 'Unknown League',
      }));

      const result: GetRacesPageDataResult = {
        leagueId: input.leagueId,
        races,
      };

      return Result.ok(result);
    } catch (error: unknown) {
      const message =
        error instanceof Error && error.message
          ? error.message
          : 'Failed to load races page data';

      this.logger.error(
        'GetRacesPageDataUseCase:execution error',
        error instanceof Error ? error : new Error(message),
      );

      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message },
      });
    }
  }
}