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

export type GetLeagueFullConfigInput = {
  leagueId: string;
};

export type LeagueFullConfig = {
  league: unknown;
  activeSeason?: unknown;
  scoringConfig?: unknown | null;
  game?: unknown | null;
};

export type GetLeagueFullConfigResult = {
  config: LeagueFullConfig;
};

export type GetLeagueFullConfigErrorCode = 'LEAGUE_NOT_FOUND' | 'REPOSITORY_ERROR';

/**
 * Use Case for retrieving a league's full configuration.
 * Orchestrates domain logic and returns the configuration data.
 */
export class GetLeagueFullConfigUseCase {
  constructor(
    private readonly leagueRepository: ILeagueRepository,
    private readonly seasonRepository: ISeasonRepository,
    private readonly leagueScoringConfigRepository: ILeagueScoringConfigRepository,
    private readonly gameRepository: IGameRepository,
    private readonly output: UseCaseOutputPort<GetLeagueFullConfigResult>,
  ) {}

  async execute(
    input: GetLeagueFullConfigInput,
  ): Promise<Result<void, ApplicationErrorCode<GetLeagueFullConfigErrorCode, { message: string }>>> {
    const { leagueId } = input;

    try {
      const league = await this.leagueRepository.findById(leagueId);
      if (!league) {
        return Result.err({
          code: 'LEAGUE_NOT_FOUND',
          details: { message: 'League not found' },
        });
      }

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

      const scoringConfig = await (async () => {
        if (!activeSeason) return null;
        return (await this.leagueScoringConfigRepository.findBySeasonId(activeSeason.id)) ?? null;
      })();

      const game = await (async () => {
        if (!activeSeason || !activeSeason.gameId) return null;
        return (await this.gameRepository.findById(activeSeason.gameId)) ?? null;
      })();

      const config: LeagueFullConfig = {
        league,
        ...(activeSeason ? { activeSeason } : {}),
        ...(scoringConfig !== null ? { scoringConfig } : {}),
        ...(game !== null ? { game } : {}),
      };

      const result: GetLeagueFullConfigResult = {
        config,
      };

      this.output.present(result);
      return Result.ok(undefined);
    } catch (error) {
      const message =
        error instanceof Error && error.message
          ? error.message
          : 'Failed to load league full configuration';

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