import type { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
import type { ILeagueMembershipRepository } from '../../domain/repositories/ILeagueMembershipRepository';
import type { ISeasonRepository } from '../../domain/repositories/ISeasonRepository';
import type { ILeagueScoringConfigRepository } from '../../domain/repositories/ILeagueScoringConfigRepository';
import type { IGameRepository } from '../../domain/repositories/IGameRepository';
import type { LeagueScoringPresetProvider } from '../ports/LeagueScoringPresetProvider';
import type { LeagueEnrichedData } from '../presenters/IAllLeaguesWithCapacityAndScoringPresenter';
import { Result } from '@core/shared/application/Result';

/**
 * Use Case for retrieving all leagues with capacity and scoring information.
 * Orchestrates domain logic and delegates presentation to the presenter.
 */
export class GetAllLeaguesWithCapacityAndScoringUseCase
{
  constructor(
    private readonly leagueRepository: ILeagueRepository,
    private readonly leagueMembershipRepository: ILeagueMembershipRepository,
    private readonly seasonRepository: ISeasonRepository,
    private readonly leagueScoringConfigRepository: ILeagueScoringConfigRepository,
    private readonly gameRepository: IGameRepository,
    private readonly presetProvider: LeagueScoringPresetProvider,
  ) {}

  async execute(): Promise<Result<LeagueEnrichedData[]>> {
    const leagues = await this.leagueRepository.findAll();

    const enrichedLeagues: LeagueEnrichedData[] = [];

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

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

      const seasons = await this.seasonRepository.findByLeagueId(league.id);
      const activeSeason =
        seasons && seasons.length > 0
          ? seasons.find((s) => s.status === 'active') ?? seasons[0]
          : undefined;

      let scoringConfig: LeagueEnrichedData['scoringConfig'];
      let game: LeagueEnrichedData['game'];
      let preset: LeagueEnrichedData['preset'];

      if (activeSeason) {
        const scoringConfigResult =
          await this.leagueScoringConfigRepository.findBySeasonId(activeSeason.id);
        scoringConfig = scoringConfigResult ?? undefined;
        if (scoringConfig) {
          const gameResult = await this.gameRepository.findById(activeSeason.gameId);
          game = gameResult ?? undefined;
          const presetId = scoringConfig.scoringPresetId;
          if (presetId) {
            preset = this.presetProvider.getPresetById(presetId);
          }
        }
      }

      enrichedLeagues.push({
        league,
        usedDriverSlots,
        ...(activeSeason ? { season: activeSeason } : {}),
        ...(scoringConfig ? { scoringConfig } : {}),
        ...(game ? { game } : {}),
        ...(preset ? { preset } : {}),
      });
    }
return Result.ok(enrichedLeagues);

  }
}