import type { IRaceRegistrationRepository } from '@core/racing/domain/repositories/IRaceRegistrationRepository';
import type { IRaceRepository } from '@core/racing/domain/repositories/IRaceRepository';
import type { RaceRegistration } from '@core/racing/domain/entities/RaceRegistration';
import type { Race } from '@core/racing/domain/entities/Race';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { UseCaseOutputPort } from '@core/shared/application/UseCaseOutputPort';

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: IRaceRepository,
    private readonly registrationRepository: IRaceRegistrationRepository,
    private readonly output: UseCaseOutputPort<GetRaceRegistrationsResult>,
  ) {}

  async execute(
    input: GetRaceRegistrationsInput,
  ): Promise<Result<void, 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,
      };

      this.output.present(result);

      return Result.ok(undefined);
    } 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 },
      });
    }
  }
}