import type { IRaceRepository } from '../../domain/repositories/IRaceRepository';
import type { AsyncUseCase } from '@core/shared/application';
import type { Logger } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { CancelRaceCommandDTO } from '../dto/CancelRaceCommandDTO';

/**
 * Use Case: CancelRaceUseCase
 *
 * Encapsulates the workflow for cancelling a race:
 * - loads the race by id
 * - returns error if the race does not exist
 * - delegates cancellation rules to the Race domain entity
 * - persists the updated race via the repository.
 */
export class CancelRaceUseCase
  implements AsyncUseCase<CancelRaceCommandDTO, void, string> {
  constructor(
    private readonly raceRepository: IRaceRepository,
    private readonly logger: Logger,
  ) {}

  async execute(command: CancelRaceCommandDTO): Promise<Result<void, ApplicationErrorCode<string>>> {
    const { raceId } = command;
    this.logger.debug(`[CancelRaceUseCase] Executing for raceId: ${raceId}`);

    try {
      const race = await this.raceRepository.findById(raceId);
      if (!race) {
        this.logger.warn(`[CancelRaceUseCase] Race with ID ${raceId} not found.`);
        return Result.err({ code: 'RACE_NOT_FOUND' });
      }

      const cancelledRace = race.cancel();
      await this.raceRepository.update(cancelledRace);
      this.logger.info(`[CancelRaceUseCase] Race ${raceId} cancelled successfully.`);
      return Result.ok(undefined);
    } catch (error) {
      if (error instanceof Error && error.message.includes('already cancelled')) {
        this.logger.warn(`[CancelRaceUseCase] Domain error cancelling race ${raceId}: ${error.message}`);
        return Result.err({ code: 'RACE_ALREADY_CANCELLED' });
      }
      if (error instanceof Error && error.message.includes('completed race')) {
        this.logger.warn(`[CancelRaceUseCase] Domain error cancelling race ${raceId}: ${error.message}`);
        return Result.err({ code: 'CANNOT_CANCEL_COMPLETED_RACE' });
      }
      this.logger.error(`[CancelRaceUseCase] Unexpected error cancelling race ${raceId}`, error instanceof Error ? error : new Error(String(error)));
      return Result.err({ code: 'UNEXPECTED_ERROR' });
    }
  }
}