import type { IRaceRegistrationRepository } from '../../domain/repositories/IRaceRegistrationRepository';
import type { Logger, UseCase, UseCaseOutputPort } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

export type IsDriverRegisteredForRaceErrorCode = 'REPOSITORY_ERROR';

type IsDriverRegisteredForRaceApplicationError = ApplicationErrorCode<
  IsDriverRegisteredForRaceErrorCode,
  { message: string }
>;

export type IsDriverRegisteredForRaceInput = {
  raceId: string;
  driverId: string;
};

export type IsDriverRegisteredForRaceResult = {
  raceId: string;
  driverId: string;
  isRegistered: boolean;
};

/**
 * Use Case: IsDriverRegisteredForRaceUseCase
 *
 * Checks if a driver is registered for a specific race.
 */
export class IsDriverRegisteredForRaceUseCase implements UseCase<IsDriverRegisteredForRaceInput, void, IsDriverRegisteredForRaceErrorCode> {
  constructor(
    private readonly registrationRepository: IRaceRegistrationRepository,
    private readonly logger: Logger,
    private readonly output: UseCaseOutputPort<IsDriverRegisteredForRaceResult>,
  ) {}

  async execute(params: IsDriverRegisteredForRaceInput): Promise<Result<void, IsDriverRegisteredForRaceApplicationError>> {
    this.logger.debug('IsDriverRegisteredForRaceUseCase:execute', { params });
    const { raceId, driverId } = params;

    try {
      const isRegistered = await this.registrationRepository.isRegistered(raceId, driverId);

      this.output.present({ isRegistered, raceId, driverId });
      return Result.ok(void 0);
    } catch (error) {
      this.logger.error(
        'IsDriverRegisteredForRaceUseCase:execution error',
        error instanceof Error ? error : new Error('Unknown error'),
      );
      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message: error instanceof Error ? error.message : 'Unknown error' },
      });
    }
  }
}