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

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: IRaceRepository,
    private readonly logger: Logger,
    private readonly output: UseCaseOutputPort<CancelRaceResult>,
  ) {}

  async execute(command: CancelRaceInput): Promise<
    Result<void, ApplicationErrorCode<CancelRaceErrorCode>>
  > {
    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,
      };

      this.output.present(result);

      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: '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),
        },
      });
    }
  }
}