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

export type GetTotalLeaguesInput = {};

export type GetTotalLeaguesResult = {
  totalLeagues: number;
};

export type GetTotalLeaguesErrorCode = 'REPOSITORY_ERROR';

export class GetTotalLeaguesUseCase {
  constructor(
    private readonly leagueRepository: ILeagueRepository,
    private readonly output: UseCaseOutputPort<GetTotalLeaguesResult>,
  ) {}

  async execute(
    _input: GetTotalLeaguesInput,
  ): Promise<Result<void, ApplicationErrorCode<GetTotalLeaguesErrorCode, { message: string }>>> {
    void _input;
    try {
      const leagues = await this.leagueRepository.findAll();
      const result: GetTotalLeaguesResult = { totalLeagues: leagues.length };

      this.output.present(result);

      return Result.ok(undefined);
    } catch (err) {
      const error = err as { message?: string } | undefined;

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