import type { Logger } from '@core/shared/domain/Logger'; import { Result } from '@core/shared/domain/Result'; import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode'; import { Result as RaceResult } from '../../domain/entities/result/Result'; import { DriverRepository } from '../../domain/repositories/DriverRepository'; import { LeagueRepository } from '../../domain/repositories/LeagueRepository'; import { RaceRepository } from '../../domain/repositories/RaceRepository'; import { ResultRepository } from '../../domain/repositories/ResultRepository'; import { StandingRepository } from '../../domain/repositories/StandingRepository'; 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: RaceRepository, private readonly leagueRepository: LeagueRepository, private readonly resultRepository: ResultRepository, private readonly driverRepository: DriverRepository, private readonly standingRepository: StandingRepository, private readonly logger: Logger, ) {} async execute( input: ImportRaceResultsInput, ): Promise>> { 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[] = 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: [], }; return Result.ok(result); } 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 }, }); } } }