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';
import type { ImportRaceResultsApiResultDTO } from '../presenters/IImportRaceResultsApiPresenter';

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

type ImportRaceResultsApiErrorCode =
  | 'PARSE_ERROR'
  | 'RACE_NOT_FOUND'
  | 'LEAGUE_NOT_FOUND'
  | 'RESULTS_EXIST'
  | 'DRIVER_NOT_FOUND'
  | 'REPOSITORY_ERROR';

type ImportRaceResultsApiApplicationError = ApplicationErrorCode<ImportRaceResultsApiErrorCode, { message: string }>;

export class ImportRaceResultsApiUseCase implements AsyncUseCase<{ raceId: string; resultsFileContent: string }, ImportRaceResultsApiResultDTO, ImportRaceResultsApiErrorCode> {
  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: { raceId: string; resultsFileContent: string }): Promise<SharedResult<ImportRaceResultsApiResultDTO, ApplicationErrorCode<ImportRaceResultsApiErrorCode>>> {
    this.logger.debug('ImportRaceResultsApiUseCase:execute', { raceId: params.raceId });
    const { raceId, resultsFileContent } = params;

    let results: ImportRaceResultDTO[];
    try {
      results = JSON.parse(resultsFileContent);
    } catch (error) {
      this.logger.error('ImportRaceResultsApiUseCase:parse error', error instanceof Error ? error : new Error('Parse error'));
      return SharedResult.err({ code: 'PARSE_ERROR', details: { message: 'Invalid JSON in results file content' } });
    }

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

      const league = await this.leagueRepository.findById(race.leagueId);
      if (!league) {
        this.logger.warn(`ImportRaceResultsApiUseCase: 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(`ImportRaceResultsApiUseCase: League ${league.id} found.`);

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

      // Lookup drivers by iracingId and create results with driver.id
      const entities: SharedResult<Result, ImportRaceResultsApiApplicationError>[] = await Promise.all(
        results.map(async (dto) => {
          const driver = await this.driverRepository.findByIRacingId(dto.driverId);
          if (!driver) {
            this.logger.warn(`ImportRaceResultsApiUseCase: 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 ImportRaceResultsApiApplicationError).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('ImportRaceResultsApiUseCase:entities created', { count: validEntities.length });

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

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

      const dto: ImportRaceResultsApiResultDTO = {
        success: true,
        raceId,
        driversProcessed: results.length,
        resultsRecorded: validEntities.length,
        errors: [],
      };

      return SharedResult.ok(dto);
    } catch (error) {
      this.logger.error('ImportRaceResultsApiUseCase: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' } });
    }
  }
}