import type { IDriverRepository } from '../../domain/repositories/IDriverRepository';
import type { TotalDriversResultDTO } from '../presenters/ITotalDriversPresenter';
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';

/**
 * Use Case for retrieving total number of drivers.
 */
export class GetTotalDriversUseCase implements AsyncUseCase<void, TotalDriversResultDTO, 'REPOSITORY_ERROR'>
{
  constructor(
    private readonly driverRepository: IDriverRepository,
    private readonly logger: Logger,
  ) {}

  async execute(): Promise<Result<TotalDriversResultDTO, ApplicationErrorCode<'REPOSITORY_ERROR'>>> {
    try {
      const drivers = await this.driverRepository.findAll();
      const dto: TotalDriversResultDTO = {
        totalDrivers: drivers.length,
      };

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