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 as RaceResult } from '../../domain/entities/result/Result';
import type { Logger, UseCaseOutputPort } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

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

export type ImportRaceResultsApiInput = {
  raceId: string;
  resultsFileContent: string;
};

export type ImportRaceResultsApiResult = {
  success: true;
  raceId: string;
  leagueId: string;
  driversProcessed: number;
  resultsRecorded: number;
  errors: string[];
};

export 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 {
  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,
    private readonly output: UseCaseOutputPort<ImportRaceResultsApiResult>,
  ) {}

  async execute(
    input: ImportRaceResultsApiInput,
  ): Promise<Result<void, ApplicationErrorCode<ImportRaceResultsApiErrorCode, { message: string }>>> {
    const { raceId, resultsFileContent } = input;

    this.logger.debug('ImportRaceResultsApiUseCase:execute', { raceId });

    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 Result.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 Result.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 Result.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 Result.err({
          code: 'RESULTS_EXIST',
          details: { message: 'Results already exist for this race' },
        });
      }

      this.logger.debug(`ImportRaceResultsApiUseCase: No existing results for race ${raceId}.`);

      const entities: Result<RaceResult, 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 Result.err({
              code: 'DRIVER_NOT_FOUND',
              details: { message: `Driver with iRacing ID ${dto.driverId} not found` },
            });
          }

          return Result.ok(
            RaceResult.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(entity => entity.isErr())
        .map(entity => (entity.error as ImportRaceResultsApiApplicationError).details.message);

      if (errors.length > 0) {
        return Result.err({
          code: 'DRIVER_NOT_FOUND',
          details: { message: errors.join('; ') },
        });
      }

      const validEntities = entities.filter(entity => entity.isOk()).map(entity => entity.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.toString());

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

      const result: ImportRaceResultsApiResult = {
        success: true,
        raceId,
        leagueId: league.id.toString(),
        driversProcessed: results.length,
        resultsRecorded: validEntities.length,
        errors: [],
      };

      this.output.present(result);

      return Result.ok(undefined);
    } catch (error: unknown) {
      this.logger.error(
        'ImportRaceResultsApiUseCase:execution error',
        error instanceof Error ? error : new Error('Unknown error'),
      );

      const message =
        error instanceof Error && error.message
          ? error.message
          : 'Failed to import race results via API';

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