import type { IRaceRegistrationRepository } from '../../domain/repositories/IRaceRegistrationRepository';
import type { IsDriverRegisteredForRaceQueryParamsDTO } from '../dto/RaceRegistrationQueryDTO';
import type { AsyncUseCase, Logger } from '@core/shared/application';
import { Result as SharedResult } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

type IsDriverRegisteredForRaceErrorCode = 'REPOSITORY_ERROR';

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

/**
 * Use Case: IsDriverRegisteredForRaceUseCase
 *
 * Checks if a driver is registered for a specific race.
 */
export class IsDriverRegisteredForRaceUseCase
  implements AsyncUseCase<IsDriverRegisteredForRaceQueryParamsDTO, boolean, IsDriverRegisteredForRaceErrorCode>
{
  constructor(
    private readonly registrationRepository: IRaceRegistrationRepository,
    private readonly logger: Logger,
  ) {}

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

    try {
      const isRegistered = await this.registrationRepository.isRegistered(raceId, driverId);
      return SharedResult.ok(isRegistered);
    } catch (error) {
      this.logger.error('IsDriverRegisteredForRaceUseCase:execution error', error instanceof Error ? error : new Error('Unknown error'));
      return SharedResult.err({ code: 'REPOSITORY_ERROR', details: { message: error instanceof Error ? error.message : 'Unknown error' } });
    }
  }
}