import type { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
import type { ILeagueMembershipRepository } from '../../domain/repositories/ILeagueMembershipRepository';
import type { AllLeaguesWithCapacityResultDTO } from '../presenters/IAllLeaguesWithCapacityPresenter';
import type { AsyncUseCase } from '@core/shared/application';
import { Result } from '@/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

/**
 * Use Case for retrieving all leagues with capacity information.
 * Orchestrates domain logic and returns result.
 */
export class GetAllLeaguesWithCapacityUseCase
  implements AsyncUseCase<void, AllLeaguesWithCapacityResultDTO, string>
{
  constructor(
    private readonly leagueRepository: ILeagueRepository,
    private readonly leagueMembershipRepository: ILeagueMembershipRepository,
  ) {}

  async execute(): Promise<Result<AllLeaguesWithCapacityResultDTO, ApplicationErrorCode<string>>> {
    const leagues = await this.leagueRepository.findAll();

    const memberCounts = new Map<string, number>();

    for (const league of leagues) {
      const members = await this.leagueMembershipRepository.getLeagueMembers(league.id);

      const usedSlots = members.filter(
        (m) =>
          m.status === 'active' &&
          (m.role === 'owner' ||
            m.role === 'admin' ||
            m.role === 'steward' ||
            m.role === 'member'),
      ).length;

      memberCounts.set(league.id, usedSlots);
    }

    const dto: AllLeaguesWithCapacityResultDTO = {
      leagues,
      memberCounts,
    };

    return Result.ok(dto);
  }
}