import { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { Result } from '@/lib/contracts/Result';
import { LeaguesApiClient } from '@/lib/api/leagues/LeaguesApiClient';
import { ConsoleErrorReporter } from '@/lib/infrastructure/logging/ConsoleErrorReporter';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';

/**
 * CreateLeaguePageQuery
 * 
 * Fetches data needed for the create league page.
 */
export class CreateLeaguePageQuery implements PageQuery<unknown, void> {
  async execute(): Promise<Result<unknown, 'notFound' | 'redirect' | 'CREATE_LEAGUE_FETCH_FAILED' | 'UNKNOWN_ERROR'>> {
    // Manual wiring: create API client
    const baseUrl = process.env.NEXT_PUBLIC_API_URL || '';
    const errorReporter = new ConsoleErrorReporter();
    const logger = new ConsoleLogger();
    const apiClient = new LeaguesApiClient(baseUrl, errorReporter, logger);
    
    try {
      // Get scoring presets for the form
      const presetsData = await apiClient.getScoringPresets();
      
      return Result.ok({
        scoringPresets: presetsData.presets || [],
      });
    } catch (error) {
      console.error('CreateLeaguePageQuery failed:', error);
      
      if (error instanceof Error) {
        if (error.message.includes('403') || error.message.includes('401')) {
          return Result.err('redirect');
        }
        if (error.message.includes('404')) {
          return Result.err('notFound');
        }
        if (error.message.includes('5') || error.message.includes('server')) {
          return Result.err('CREATE_LEAGUE_FETCH_FAILED');
        }
      }
      
      return Result.err('UNKNOWN_ERROR');
    }
  }

  static async execute(): Promise<Result<unknown, 'notFound' | 'redirect' | 'CREATE_LEAGUE_FETCH_FAILED' | 'UNKNOWN_ERROR'>> {
    const query = new CreateLeaguePageQuery();
    return query.execute();
  }
}