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 ReopenRaceInput = {
  raceId: string;
  reopenedById: string;
};

export type ReopenRaceErrorCode =
  | 'RACE_NOT_FOUND'
  | 'UNAUTHORIZED'
  | 'INVALID_RACE_STATE'
  | 'REPOSITORY_ERROR';

export type ReopenRaceResult = {
  race: Race;
};

/**
 * Use Case: ReopenRaceUseCase
 *
 * Encapsulates the workflow for re-opening a race:
 * - loads the race by id
 * - returns error if the race does not exist
 * - delegates transition rules to the Race domain entity via `reopen()`
 * - persists the updated race via the repository.
 */
export class ReopenRaceUseCase {
  constructor(
    private readonly raceRepository: RaceRepository,
    private readonly logger: Logger,
  ) {}

  async execute(
    input: ReopenRaceInput,
  ): Promise<Result<ReopenRaceResult, ApplicationErrorCode<ReopenRaceErrorCode, { message: string }>>> {
    const { raceId } = input;
    this.logger.debug(`[ReopenRaceUseCase] Executing for raceId: ${raceId}`);

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

      const reopenedRace = race.reopen();
      await this.raceRepository.update(reopenedRace);
      this.logger.info(`[ReopenRaceUseCase] Race ${raceId} re-opened successfully.`);

      const result: ReopenRaceResult = {
        race: reopenedRace,
      };

      return Result.ok(result);
    } catch (error) {
      if (error instanceof Error && error.message.includes('already scheduled')) {
        this.logger.warn(`[ReopenRaceUseCase] Domain error re-opening race ${raceId}: ${error.message}`);
        return Result.err({
          code: 'INVALID_RACE_STATE',
          details: { message: error.message },
        });
      }
      if (error instanceof Error && error.message.includes('running race')) {
        this.logger.warn(`[ReopenRaceUseCase] Domain error re-opening race ${raceId}: ${error.message}`);
        return Result.err({
          code: 'INVALID_RACE_STATE',
          details: { message: error.message },
        });
      }

      this.logger.error(
        `[ReopenRaceUseCase] Unexpected error re-opening race ${raceId}`,
        error instanceof Error ? error : new Error(String(error)),
      );

      const message = error instanceof Error ? error.message : 'Failed to reopen race';

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