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, RaceStatusValue } from '../../domain/entities/Race';
import { LeagueRepository } from '../../domain/repositories/LeagueRepository';
import { RaceRepository } from '../../domain/repositories/RaceRepository';

export type GetAllRacesPageDataInput = {};

export interface GetAllRacesPageRaceItem {
  id: string;
  track: string;
  car: string;
  scheduledAt: string;
  status: RaceStatusValue;
  leagueId: string;
  leagueName: string;
  strengthOfField: number | null;
}

export interface GetAllRacesPageDataFilters {
  statuses: { value: 'all' | RaceStatusValue; label: string }[];
  leagues: { id: string; name: string }[];
}

export interface GetAllRacesPageDataResult {
  races: GetAllRacesPageRaceItem[];
  filters: GetAllRacesPageDataFilters;
}

export type GetAllRacesPageDataErrorCode = 'REPOSITORY_ERROR';

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

  async execute(
    _input: GetAllRacesPageDataInput,
  ): Promise<Result<GetAllRacesPageDataResult, ApplicationErrorCode<GetAllRacesPageDataErrorCode, { message: string }>>> {
    void _input;
    this.logger.debug('Executing GetAllRacesPageDataUseCase');
    try {
      const [allRaces, allLeagues] = await Promise.all([
        this.raceRepository.findAll(),
        this.leagueRepository.findAll(),
      ]);
      this.logger.info(`Found ${allRaces.length} races and ${allLeagues.length} leagues.`);

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

      const races: GetAllRacesPageRaceItem[] = allRaces
        .slice()
        .sort((a: Race, b: Race) => b.scheduledAt.getTime() - a.scheduledAt.getTime())
        .map((race: 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: race.strengthOfField?.toNumber() ?? null,
        }));

      const uniqueLeagues = new Map<string, { id: string; name: string }>();
      for (const league of allLeagues) {
        uniqueLeagues.set(league.id.toString(), { id: league.id.toString(), name: league.name.toString() });
      }

      const filters: GetAllRacesPageDataFilters = {
        statuses: [
          { value: 'all', label: 'All Statuses' },
          { value: 'scheduled', label: 'Scheduled' },
          { value: 'running', label: 'Live' },
          { value: 'completed', label: 'Completed' },
          { value: 'cancelled', label: 'Cancelled' },
        ],
        leagues: Array.from(uniqueLeagues.values()),
      };

      const result: GetAllRacesPageDataResult = {
        races,
        filters,
      };

      this.logger.debug('Successfully retrieved all races page data.');
      return Result.ok(result);
    } catch (error) {
      this.logger.error(
        'Error executing GetAllRacesPageDataUseCase',
        error instanceof Error ? error : new Error(String(error)),
      );
      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message: error instanceof Error ? error.message : 'Unknown error occurred' },
      });
    }
  }
}