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

export interface GetLeagueProtestsInput {
  leagueId: string;
}

export type GetLeagueProtestsErrorCode = 'LEAGUE_NOT_FOUND' | 'REPOSITORY_ERROR';

export interface LeagueProtestWithEntities {
  protest: Protest;
  race: Race | null;
  protestingDriver: Driver | null;
  accusedDriver: Driver | null;
}

export interface GetLeagueProtestsResult {
  league: League;
  protests: LeagueProtestWithEntities[];
}

export class GetLeagueProtestsUseCase {
  constructor(
    private readonly raceRepository: RaceRepository,
    private readonly protestRepository: ProtestRepository,
    private readonly driverRepository: DriverRepository,
    private readonly leagueRepository: LeagueRepository,
  ) {}

  async execute(
    input: GetLeagueProtestsInput,
  ): Promise<Result<GetLeagueProtestsResult, ApplicationErrorCode<GetLeagueProtestsErrorCode, { message: string }>>> {
    try {
      const league = await this.leagueRepository.findById(input.leagueId);

      if (!league) {
        return Result.err({
          code: 'LEAGUE_NOT_FOUND',
          details: { message: 'League not found' },
        });
      }

      const races = await this.raceRepository.findByLeagueId(input.leagueId);
      const protests: Protest[] = [];
      const racesById: Record<string, Race> = {};
      const driversById: Record<string, Driver> = {};
      const driverIds = new Set<string>();

      for (const race of races) {
        racesById[race.id] = race;
        const raceProtests = await this.protestRepository.findByRaceId(race.id);
        for (const protest of raceProtests) {
          protests.push(protest);
          driverIds.add(protest.protestingDriverId);
          driverIds.add(protest.accusedDriverId);
        }
      }

      for (const driverId of driverIds) {
        const driver = await this.driverRepository.findById(driverId);
        if (driver) {
          driversById[driver.id] = driver;
        }
      }

      const protestsWithEntities: LeagueProtestWithEntities[] = protests.map(protest => ({
        protest,
        race: racesById[protest.raceId] ?? null,
        protestingDriver: driversById[protest.protestingDriverId] ?? null,
        accusedDriver: driversById[protest.accusedDriverId] ?? null,
      }));

      const result: GetLeagueProtestsResult = {
        league,
        protests: protestsWithEntities,
      };

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

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