import type { IRaceRepository } from '../../domain/repositories/IRaceRepository';
import type { GetTotalRacesResultDTO } from '../presenters/IGetTotalRacesPresenter';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { AsyncUseCase } from '@core/shared/application';
import type { Logger } from '@core/shared/application';

export class GetTotalRacesUseCase implements AsyncUseCase<void, GetTotalRacesResultDTO, 'REPOSITORY_ERROR'>
{
  constructor(
    private readonly raceRepository: IRaceRepository,
    private readonly logger: Logger,
  ) {}

  async execute(): Promise<Result<GetTotalRacesResultDTO, ApplicationErrorCode<'REPOSITORY_ERROR'>>> {
    try {
      const races = await this.raceRepository.findAll();
      const dto: GetTotalRacesResultDTO = { totalRaces: races.length };

      return Result.ok(dto);
    } catch (error) {
      this.logger.error('Error retrieving total races', error as Error);
      return Result.err({ code: 'REPOSITORY_ERROR', details: { message: 'Failed to retrieve total races' } });
    }
  }
}