import type { IRaceRepository } from '../../domain/repositories/IRaceRepository';
import type { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
import type { IResultRepository } from '../../domain/repositories/IResultRepository';
import type { IDriverRepository } from '../../domain/repositories/IDriverRepository';
import type { IStandingRepository } from '../../domain/repositories/IStandingRepository';
import { Result } from '../../domain/entities/Result';
import type { AsyncUseCase, Logger } from '@core/shared/application';
import { Result as SharedResult } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

export interface ImportRaceResultDTO {
  id: string;
  raceId: string;
  driverId: string;
  position: number;
  fastestLap: number;
  incidents: number;
  startPosition: number;
}

export interface ImportRaceResultsParams {
  raceId: string;
  results: ImportRaceResultDTO[];
}

type ImportRaceResultsErrorCode =
  | 'RACE_NOT_FOUND'
  | 'LEAGUE_NOT_FOUND'
  | 'RESULTS_EXIST'
  | 'DRIVER_NOT_FOUND'
  | 'REPOSITORY_ERROR';

type ImportRaceResultsApplicationError = ApplicationErrorCode<ImportRaceResultsErrorCode, { message: string }>;

export class ImportRaceResultsUseCase
  implements AsyncUseCase<ImportRaceResultsParams, void, ImportRaceResultsErrorCode>
{
  constructor(
    private readonly raceRepository: IRaceRepository,
    private readonly leagueRepository: ILeagueRepository,
    private readonly resultRepository: IResultRepository,
    private readonly driverRepository: IDriverRepository,
    private readonly standingRepository: IStandingRepository,
    private readonly logger: Logger,
  ) {}

  async execute(params: ImportRaceResultsParams): Promise<SharedResult<void, ImportRaceResultsApplicationError>> {
    this.logger.debug('ImportRaceResultsUseCase:execute', { params });
    const { raceId, results } = params;

    const race = await this.raceRepository.findById(raceId);
    if (!race) {
      this.logger.warn(`ImportRaceResultsUseCase: Race with ID ${raceId} not found.`);
      return SharedResult.err({ code: 'RACE_NOT_FOUND', details: { message: `Race ${raceId} not found` } });
    }
    this.logger.debug(`ImportRaceResultsUseCase: Race ${raceId} found.`);

    const league = await this.leagueRepository.findById(race.leagueId);
    if (!league) {
      this.logger.warn(`ImportRaceResultsUseCase: League with ID ${race.leagueId} not found for race ${raceId}.`);
      return SharedResult.err({ code: 'LEAGUE_NOT_FOUND', details: { message: `League ${race.leagueId} not found` } });
    }
    this.logger.debug(`ImportRaceResultsUseCase: League ${league.id} found.`);

    const existing = await this.resultRepository.existsByRaceId(raceId);
    if (existing) {
      this.logger.warn(`ImportRaceResultsUseCase: Results already exist for race ID: ${raceId}.`);
      return SharedResult.err({ code: 'RESULTS_EXIST', details: { message: 'Results already exist for this race' } });
    }
    this.logger.debug(`ImportRaceResultsUseCase: No existing results for race ${raceId}.`);

    // Lookup drivers by iracingId and create results with driver.id
    const entities: SharedResult<Result, ImportRaceResultsApplicationError>[] = await Promise.all(
      results.map(async (dto) => {
        const driver = await this.driverRepository.findByIRacingId(dto.driverId);
        if (!driver) {
          this.logger.warn(`ImportRaceResultsUseCase: Driver with iRacing ID ${dto.driverId} not found for race ${raceId}.`);
          return SharedResult.err({ code: 'DRIVER_NOT_FOUND', details: { message: `Driver with iRacing ID ${dto.driverId} not found` } });
        }
        return SharedResult.ok(Result.create({
          id: dto.id,
          raceId: dto.raceId,
          driverId: driver.id,
          position: dto.position,
          fastestLap: dto.fastestLap,
          incidents: dto.incidents,
          startPosition: dto.startPosition,
        }));
      }),
    );

    const errors = entities.filter(e => e.isErr()).map(e => (e.error as ImportRaceResultsApplicationError).details.message);
    if (errors.length > 0) {
      return SharedResult.err({ code: 'DRIVER_NOT_FOUND', details: { message: errors.join('; ') } });
    }

    const validEntities = entities.filter(e => e.isOk()).map(e => e.unwrap());
    this.logger.debug('ImportRaceResultsUseCase:entities created', { count: validEntities.length });

    try {
      await this.resultRepository.createMany(validEntities);
      this.logger.info('ImportRaceResultsUseCase:race results created', { raceId });

      await this.standingRepository.recalculate(league.id);
      this.logger.info('ImportRaceResultsUseCase:standings recalculated', { leagueId: league.id });

      return SharedResult.ok(undefined);
    } catch (error) {
      this.logger.error('ImportRaceResultsUseCase:execution error', error instanceof Error ? error : new Error('Unknown error'));
      return SharedResult.err({ code: 'REPOSITORY_ERROR', details: { message: error instanceof Error ? error.message : 'Unknown error' } });
    }
  }
}
