import { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { Result } from '@/lib/contracts/Result';
import { LeaguesViewDataBuilder } from '@/lib/builders/view-data/LeaguesViewDataBuilder';
import type { LeaguesViewData } from '@/lib/view-data/LeaguesViewData';
import { LeagueService } from '@/lib/services/leagues/LeagueService';

/**
 * Leagues page query
 * Returns Result<LeaguesViewData, PresentationError>
 * No DI container usage - constructs dependencies explicitly
 */
export class LeaguesPageQuery implements PageQuery<LeaguesViewData, void> {
  async execute(): Promise<Result<LeaguesViewData, 'notFound' | 'redirect' | 'LEAGUES_FETCH_FAILED' | 'UNKNOWN_ERROR'>> {
    // Manual construction: Service creates its own dependencies
    const service = new LeagueService();

    // Fetch data using service
    const result = await service.getAllLeagues();

    if (result.isErr()) {
      const error = result.getError();
      switch (error.type) {
        case 'notFound':
          return Result.err('notFound');
        case 'unauthorized':
        case 'forbidden':
          return Result.err('redirect');
        case 'serverError':
          return Result.err('LEAGUES_FETCH_FAILED');
        default:
          return Result.err('UNKNOWN_ERROR');
      }
    }

    // Transform to ViewData using builder
    const viewData = LeaguesViewDataBuilder.build(result.unwrap());
    return Result.ok(viewData);
  }

  // Static method to avoid object construction in server code
  static async execute(): Promise<Result<LeaguesViewData, 'notFound' | 'redirect' | 'LEAGUES_FETCH_FAILED' | 'UNKNOWN_ERROR'>> {
    const query = new LeaguesPageQuery();
    return query.execute();
  }
}