import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { IRaceRegistrationRepository } from '@core/racing/domain/repositories/IRaceRegistrationRepository';
import type { WithdrawFromRaceCommandDTO } from '../dto/WithdrawFromRaceCommandDTO';

/**
 * Mirrors legacy withdrawFromRace behavior:
 * - returns error when driver is not registered
 * - removes registration and cleans up empty race sets
 *
 * The repository encapsulates the in-memory or persistent details.
 */
export class WithdrawFromRaceUseCase {
  constructor(
    private readonly registrationRepository: IRaceRegistrationRepository,
  ) {}

  async execute(command: WithdrawFromRaceCommandDTO): Promise<Result<void, ApplicationErrorCode<'NOT_REGISTERED'>>> {
    const { raceId, driverId } = command;

    try {
      await this.registrationRepository.withdraw(raceId, driverId);
      return Result.ok(undefined);
    } catch {
      return Result.err({ code: 'NOT_REGISTERED' });
    }
  }
}