import type { Race } from '@core/racing/domain/entities/Race';
import type { RaceRegistration } from '@core/racing/domain/entities/RaceRegistration';
import type { RaceRegistrationRepository } from '@core/racing/domain/repositories/RaceRegistrationRepository';
import type { RaceRepository } from '@core/racing/domain/repositories/RaceRepository';
import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

export type GetRaceRegistrationsInput = {
  raceId: string;
};

export type RaceRegistrationWithContext = {
  registration: RaceRegistration;
};

export type GetRaceRegistrationsResult = {
  race: Race;
  registrations: RaceRegistrationWithContext[];
};

export type GetRaceRegistrationsErrorCode = 'RACE_NOT_FOUND' | 'REPOSITORY_ERROR';

export class GetRaceRegistrationsUseCase {
  constructor(
    private readonly raceRepository: RaceRepository,
    private readonly registrationRepository: RaceRegistrationRepository,
  ) {}

  async execute(
    input: GetRaceRegistrationsInput,
  ): Promise<Result<GetRaceRegistrationsResult, ApplicationErrorCode<GetRaceRegistrationsErrorCode, { message: string }>>> {
    const { raceId } = input;

    try {
      const race = await this.raceRepository.findById(raceId);

      if (!race) {
        return Result.err({
          code: 'RACE_NOT_FOUND',
          details: { message: 'Race not found' },
        });
      }

      const registrations = await this.registrationRepository.findByRaceId(raceId);

      const registrationsWithContext: RaceRegistrationWithContext[] = registrations.map(registration => ({
        registration,
      }));

      const result: GetRaceRegistrationsResult = {
        race,
        registrations: registrationsWithContext,
      };

      return Result.ok(result);
    } catch (error: unknown) {
      const message =
        error instanceof Error && error.message
          ? error.message
          : 'Failed to load race registrations';

      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message },
      });
    }
  }
}