import type { IRaceRegistrationRepository } from '@core/racing/domain/repositories/IRaceRegistrationRepository';
import type { ILeagueMembershipRepository } from '@core/racing/domain/repositories/ILeagueMembershipRepository';
import { RaceRegistration } from '@core/racing/domain/entities/RaceRegistration';
import type { AsyncUseCase } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { Logger } from '@core/shared/application';

export interface RegisterForRaceParams {
  raceId: string;
  leagueId: string;
  driverId: string;
}

type RegisterForRaceErrorCode = 'ALREADY_REGISTERED' | 'NOT_ACTIVE_MEMBER';

export class RegisterForRaceUseCase
  implements AsyncUseCase<RegisterForRaceParams, void, RegisterForRaceErrorCode>
{
  constructor(
    private readonly registrationRepository: IRaceRegistrationRepository,
    private readonly membershipRepository: ILeagueMembershipRepository,
    private readonly logger: Logger,
  ) {}

  /**
   * Mirrors legacy registerForRace behavior:
   * - returns error if already registered
   * - validates active league membership
   * - registers driver for race
   */
  async execute(params: RegisterForRaceParams): Promise<Result<void, ApplicationErrorCode<RegisterForRaceErrorCode>>> {
    const { raceId, leagueId, driverId } = params;
    this.logger.debug('RegisterForRaceUseCase: executing params', { raceId, leagueId, driverId });

    const alreadyRegistered = await this.registrationRepository.isRegistered(raceId, driverId);
    if (alreadyRegistered) {
      this.logger.warn(`RegisterForRaceUseCase: driver ${driverId} already registered for race ${raceId}`);
      return Result.err({ code: 'ALREADY_REGISTERED', details: { message: 'Already registered for this race' } });
    }

    const membership = await this.membershipRepository.getMembership(leagueId, driverId);
    if (!membership || membership.status !== 'active') {
      this.logger.error(`RegisterForRaceUseCase: driver ${driverId} not an active member of league ${leagueId}`);
      return Result.err({ code: 'NOT_ACTIVE_MEMBER', details: { message: 'Must be an active league member to register for races' } });
    }

    const registration = RaceRegistration.create({
      raceId,
      driverId,
    });

    await this.registrationRepository.register(registration);
    this.logger.info(`RegisterForRaceUseCase: driver ${driverId} successfully registered for race ${raceId}`);

    return Result.ok(undefined);
  }
}