import { Result } from '@/lib/contracts/Result';
import { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { PresentationError, mapToPresentationError } from '@/lib/contracts/page-queries/PresentationError';
import { RaceResultsViewData } from '@/lib/view-data/races/RaceResultsViewData';
import { RaceResultsService } from '@/lib/services/races/RaceResultsService';
import { RaceResultsViewDataBuilder } from '@/lib/builders/view-data/RaceResultsViewDataBuilder';

interface RaceResultsPageQueryParams {
  raceId: string;
  driverId?: string;
}

/**
 * Race Results Page Query
 * 
 * Fetches race results data for the race results page.
 * Returns Result<RaceResultsViewData, PresentationError>
 */
export class RaceResultsPageQuery implements PageQuery<RaceResultsViewData, RaceResultsPageQueryParams> {
  async execute(params: RaceResultsPageQueryParams): Promise<Result<RaceResultsViewData, PresentationError>> {
    // Manual wiring: Service creates its own dependencies
    const service = new RaceResultsService();
    
    // Get race results data
    const result = await service.getRaceResultsDetail(params.raceId);
    
    if (result.isErr()) {
      return Result.err(mapToPresentationError(result.getError()));
    }
    
    // Transform to ViewData using builder
    const viewData = RaceResultsViewDataBuilder.build(result.unwrap());
    return Result.ok(viewData);
  }

  // Static method to avoid object construction in server code
  static async execute(params: RaceResultsPageQueryParams): Promise<Result<RaceResultsViewData, PresentationError>> {
    const query = new RaceResultsPageQuery();
    return await query.execute(params);
  }
}