import type { Logger } from '@core/shared/domain/Logger';
import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { Race } from '../../domain/entities/Race';
import { RaceRepository } from '../../domain/repositories/RaceRepository';

export type CancelRaceInput = {
  raceId: string;
  cancelledById: string;
};

export type CancelRaceErrorCode = 'RACE_NOT_FOUND' | 'NOT_AUTHORIZED' | 'REPOSITORY_ERROR';

export type CancelRaceResult = {
  race: Race;
};

/**
 * 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 {
  constructor(
    private readonly raceRepository: RaceRepository,
    private readonly logger: Logger,
  ) {}

  async execute(command: CancelRaceInput): Promise<
    Result<CancelRaceResult, ApplicationErrorCode<CancelRaceErrorCode, { message: 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',
          details: { message: 'Race not found' }
        });
      }

      const cancelledRace = race.cancel();
      await this.raceRepository.update(cancelledRace);
      this.logger.info(`[CancelRaceUseCase] Race ${raceId} cancelled successfully.`);

      const result: CancelRaceResult = {
        race: cancelledRace,
      };

      return Result.ok(result);
    } 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: 'NOT_AUTHORIZED',
          details: { message: error.message },
        });
      }
      if (error instanceof Error && error.message.includes('completed race')) {
        this.logger.warn(`[CancelRaceUseCase] Domain error cancelling race ${raceId}: ${error.message}`);
        return Result.err({
          code: 'NOT_AUTHORIZED',
          details: { message: error.message },
        });
      }
      this.logger.error(
        `[CancelRaceUseCase] Unexpected error cancelling race ${raceId}`,
        error instanceof Error ? error : new Error(String(error)),
      );
      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: {
          message: error instanceof Error ? error.message : String(error),
        },
      });
    }
  }
}