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 ImportRaceResultRow = {
  id: string;
  driverExternalId: string;
  position: number;
  fastestLap: number;
  incidents: number;
  startPosition: number;
};

export type ImportRaceResultsInput = {
  raceId: string;
  rows: ImportRaceResultRow[];
};

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

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

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

export class ImportRaceResultsUseCase {
  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<ImportRaceResultsResult>,
  ) {}

  async execute(
    input: ImportRaceResultsInput,
  ): Promise<Result<void, ApplicationErrorCode<ImportRaceResultsErrorCode, { message: string }>>> {
    const { raceId, rows } = input;

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

    try {
      const race = await this.raceRepository.findById(raceId);

      if (!race) {
        this.logger.warn(`ImportRaceResultsUseCase: Race with ID ${raceId} not found.`);

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

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

      const entities: Result<RaceResult, ImportRaceResultsApplicationError>[] = await Promise.all(
        rows.map(async row => {
          const driver = await this.driverRepository.findByIRacingId(row.driverExternalId);

          if (!driver) {
            this.logger.warn(
              `ImportRaceResultsUseCase: Driver with iRacing ID ${row.driverExternalId} not found for race ${raceId}.`,
            );

            return Result.err({
              code: 'DRIVER_NOT_FOUND',
              details: { message: `Driver with iRacing ID ${row.driverExternalId} not found` },
            });
          }

          return Result.ok(
            RaceResult.create({
              id: row.id,
              raceId,
              driverId: driver.id,
              position: row.position,
              fastestLap: row.fastestLap,
              incidents: row.incidents,
              startPosition: row.startPosition,
            }),
          );
        }),
      );

      const errors = entities
        .filter(entity => entity.isErr())
        .map(entity => (entity.error as ImportRaceResultsApplicationError).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('ImportRaceResultsUseCase:entities created', {
        count: validEntities.length,
      });

      await this.resultRepository.createMany(validEntities);

      this.logger.info('ImportRaceResultsUseCase:race results created', { raceId });

      await this.standingRepository.recalculate(league.id.toString());

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

      const result: ImportRaceResultsResult = {
        raceId,
        leagueId: league.id.toString(),
        driversProcessed: rows.length,
        resultsRecorded: validEntities.length,
        errors: [],
      };

      this.output.present(result);

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

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

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