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 { League } from '../../domain/entities/League';
import type { Season } from '../../domain/entities/season/Season';
import type { LeagueScoringConfig } from '../../domain/entities/LeagueScoringConfig';
import type { Game } from '../../domain/entities/Game';
import type { LeagueScoringPreset } from '../../domain/types/LeagueScoringPreset';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { UseCaseOutputPort } from '@core/shared/application/UseCaseOutputPort';

export type GetAllLeaguesWithCapacityAndScoringInput = {};

export type LeagueCapacityAndScoringSummary = {
  league: League;
  currentDrivers: number;
  maxDrivers: number;
  season?: Season;
  scoringConfig?: LeagueScoringConfig;
  game?: Game;
  preset?: LeagueScoringPreset;
};

export type GetAllLeaguesWithCapacityAndScoringResult = {
  leagues: LeagueCapacityAndScoringSummary[];
};

export type GetAllLeaguesWithCapacityAndScoringErrorCode = 'REPOSITORY_ERROR';

/**
 * Use Case for retrieving all leagues with capacity and scoring information.
 * Orchestrates domain logic and delegates presentation to an output port.
 */
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: { getPresetById(presetId: string): LeagueScoringPreset | undefined },
    private readonly output: UseCaseOutputPort<GetAllLeaguesWithCapacityAndScoringResult>,
  ) {}

  async execute(
    _input: GetAllLeaguesWithCapacityAndScoringInput = {},
  ): Promise<
    Result<
      void,
      ApplicationErrorCode<
        GetAllLeaguesWithCapacityAndScoringErrorCode,
        { message: string }
      >
    >
  > {
    void _input;
    try {
      const leagues = await this.leagueRepository.findAll();

      const enrichedLeagues: LeagueCapacityAndScoringSummary[] = [];

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

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

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

        let scoringConfig: LeagueScoringConfig | undefined;
        let game: Game | undefined;
        let preset: LeagueScoringPreset | undefined;

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

        const maxDrivers = league.settings.maxDrivers ?? 0;

        enrichedLeagues.push({
          league,
          currentDrivers,
          maxDrivers,
          ...(activeSeason ? { season: activeSeason } : {}),
          ...(scoringConfig ? { scoringConfig } : {}),
          ...(game ? { game } : {}),
          ...(preset ? { preset } : {}),
        });
      }

      await this.output.present({ leagues: enrichedLeagues });

      return Result.ok(undefined);
    } catch (error: unknown) {
      const message =
        error instanceof Error && error.message
          ? error.message
          : 'Failed to load leagues with capacity and scoring';

      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message },
      });
    }
  }
}