import type { UseCase } from '@core/shared/application/UseCase';
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 { RaceRegistrationRepository } from '../../domain/repositories/RaceRegistrationRepository';

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, IsDriverRegisteredForRaceResult, IsDriverRegisteredForRaceErrorCode> {
  constructor(
    private readonly registrationRepository: RaceRegistrationRepository,
    private readonly logger: Logger,
  ) {}

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

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

      const result: IsDriverRegisteredForRaceResult = { isRegistered, raceId, driverId };
      return Result.ok(result);
    } 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' },
      });
    }
  }
}