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

export type GetTotalRacesInput = {};

export interface GetTotalRacesResult {
  totalRaces: number;
}

export type GetTotalRacesErrorCode = 'REPOSITORY_ERROR';

export class GetTotalRacesUseCase {
  constructor(
    private readonly raceRepository: IRaceRepository,
    private readonly logger: Logger,
    private readonly output: UseCaseOutputPort<GetTotalRacesResult>,
  ) {}

  async execute(_input: GetTotalRacesInput): Promise<
    Result<void, ApplicationErrorCode<GetTotalRacesErrorCode, { message: string }>>
  > {
    void _input;
    try {
      const races = await this.raceRepository.findAll();

      this.output.present({ totalRaces: races.length });

      return Result.ok(undefined);
    } catch (error) {
      const err = error as Error;

      this.logger.error('Error retrieving total races', err);

      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message: err.message ?? 'Failed to compute total races' },
      });
    }
  }
}
