import type { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
import type { GetTotalLeaguesResultDTO } from '../presenters/IGetTotalLeaguesPresenter';
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 GetTotalLeaguesUseCase implements AsyncUseCase<void, GetTotalLeaguesResultDTO, 'REPOSITORY_ERROR'>
{
  constructor(
    private readonly leagueRepository: ILeagueRepository,
    private readonly logger: Logger,
  ) {}

  async execute(): Promise<Result<GetTotalLeaguesResultDTO, ApplicationErrorCode<'REPOSITORY_ERROR'>>> {
    try {
      const leagues = await this.leagueRepository.findAll();
      const dto: GetTotalLeaguesResultDTO = { totalLeagues: leagues.length };

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