import type { IRaceRepository } from '../../domain/repositories/IRaceRepository';
import type { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { Logger } from '@core/shared/application';
import type { UseCaseOutputPort } from '@core/shared/application/UseCaseOutputPort';
import type { Race } from '../../domain/entities/Race';
import type { League } from '../../domain/entities/League';

export type GetAllRacesInput = {};

export interface GetAllRacesResult {
  races: Race[];
  leagues: League[];
  totalCount: number;
}

export type GetAllRacesErrorCode = 'REPOSITORY_ERROR';

export class GetAllRacesUseCase {
  private output: UseCaseOutputPort<GetAllRacesResult> | null = null;

  constructor(
    private readonly raceRepository: IRaceRepository,
    private readonly leagueRepository: ILeagueRepository,
    private readonly logger: Logger,
  ) {}

  setOutput(output: UseCaseOutputPort<GetAllRacesResult>) {
    this.output = output;
  }

  async execute(
    _input: GetAllRacesInput,
  ): Promise<Result<void, ApplicationErrorCode<GetAllRacesErrorCode, { message: string }>>> {
    void _input;
    this.logger.debug('Executing GetAllRacesUseCase');
    try {
      const races = await this.raceRepository.findAll();
      const leagues = await this.leagueRepository.findAll();

      const result: GetAllRacesResult = {
        races,
        leagues,
        totalCount: races.length,
      };

      this.logger.debug('Successfully retrieved all races.');
      if (!this.output) {
        throw new Error('Output not set');
      }
      this.output.present(result);
      return Result.ok(undefined);
    } catch (error) {
      this.logger.error(
        'Error executing GetAllRacesUseCase',
        error instanceof Error ? error : new Error(String(error)),
      );
      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message: error instanceof Error ? error.message : 'Unknown error occurred' },
      });
    }
  }
}
