import type { Logger } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { UseCaseOutputPort } from '@core/shared/application/UseCaseOutputPort';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { Race } from '../../domain/entities/Race';
import type { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
import type { IRaceRepository } from '../../domain/repositories/IRaceRepository';

export type 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: IRaceRepository,
    private readonly leagueRepository: ILeagueRepository,
    private readonly logger: Logger,
    private readonly output: UseCaseOutputPort<GetRacesPageDataResult>,
  ) {}

  async execute(
    input: GetRacesPageDataInput,
  ): Promise<Result<void, 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.id.toString(), league.name.toString()]),
      );

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

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

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

      this.output.present(result);

      return Result.ok(undefined);
    } 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 },
      });
    }
  }
}
