import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { GameRepository } from '../../domain/repositories/GameRepository';
import type { LeagueRepository } from '../../domain/repositories/LeagueRepository';
import type { LeagueScoringConfigRepository } from '../../domain/repositories/LeagueScoringConfigRepository';
import type { SeasonRepository } from '../../domain/repositories/SeasonRepository';

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: LeagueRepository,
    private readonly seasonRepository: SeasonRepository,
    private readonly leagueScoringConfigRepository: LeagueScoringConfigRepository,
    private readonly gameRepository: GameRepository) {}

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

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

      console.log('League settings:', JSON.stringify(league.settings, null, 2));

      const seasons = await this.seasonRepository.findByLeagueId(leagueId);
      console.log('Seasons found:', seasons?.length);
      const activeSeason =
        seasons && seasons.length > 0
          ? seasons.find((s) => s.status.isActive()) ?? seasons[0]
          : undefined;
      console.log('Active season:', activeSeason?.id);

      const scoringConfig = await (async () => {
        if (!activeSeason) return null;
        console.log('Getting scoring config for season:', activeSeason.id);
        try {
          const result = await this.leagueScoringConfigRepository.findBySeasonId(activeSeason.id);
          console.log('Scoring config result:', result);
          return result ?? null;
        } catch (error) {
          console.error('Error getting scoring config for season:', activeSeason.id, error);
          throw error;
        }
      })();

      const game = await (async () => {
        if (!activeSeason || !activeSeason.gameId) return null;
        console.log('Getting game for game ID:', activeSeason.gameId);
        try {
          const result = await this.gameRepository.findById(activeSeason.gameId);
          console.log('Game result:', result);
          return result ?? null;
        } catch (error) {
          console.error('Error getting game for game ID:', activeSeason.gameId, error);
          throw error;
        }
      })();

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

      const result: GetLeagueFullConfigResult = {
        config,
      };

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

      console.error('GetLeagueFullConfigUseCase error:', error);
      console.error('Error stack:', error instanceof Error ? error.stack : 'No stack trace');

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