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

/**
 * LeagueProtestReviewPageQuery
 * 
 * Fetches protest detail data for review.
 */
export class LeagueProtestReviewPageQuery implements PageQuery<unknown, { leagueId: string; protestId: string }> {
  async execute(input: { leagueId: string; protestId: string }): Promise<Result<unknown, 'notFound' | 'redirect' | 'PROTEST_FETCH_FAILED' | 'UNKNOWN_ERROR'>> {
    // Manual wiring: create API clients
    const baseUrl = process.env.NEXT_PUBLIC_API_URL || '';
    const errorReporter = new ConsoleErrorReporter();
    const logger = new ConsoleLogger();
    new LeaguesApiClient(baseUrl, errorReporter, logger);
    new ProtestsApiClient(baseUrl, errorReporter, logger);
    
    try {
      // Get protest details
      // Note: This would need a getProtestDetail method on ProtestsApiClient
      // For now, return placeholder data
      const protestDetail = {
        protest: {
          id: input.protestId,
          raceId: 'placeholder',
          protestingDriverId: 'placeholder',
          accusedDriverId: 'placeholder',
          description: 'Placeholder protest',
          status: 'pending',
          submittedAt: new Date().toISOString(),
        },
        race: {
          id: 'placeholder',
          name: 'Placeholder Race',
          scheduledAt: new Date().toISOString(),
        },
        protestingDriver: {
          id: 'placeholder',
          name: 'Placeholder Protester',
        },
        accusedDriver: {
          id: 'placeholder',
          name: 'Placeholder Accused',
        },
        penaltyTypes: [],
        defaultReasons: {},
      };
      
      return Result.ok(protestDetail);
    } catch (error) {
      console.error('LeagueProtestReviewPageQuery 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('PROTEST_FETCH_FAILED');
        }
      }
      
      return Result.err('UNKNOWN_ERROR');
    }
  }

  static async execute(input: { leagueId: string; protestId: string }): Promise<Result<unknown, 'notFound' | 'redirect' | 'PROTEST_FETCH_FAILED' | 'UNKNOWN_ERROR'>> {
    const query = new LeagueProtestReviewPageQuery();
    return query.execute(input);
  }
}