import { Result } from '@/lib/contracts/Result';
import { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { PresentationError, mapToPresentationError } from '@/lib/contracts/page-queries/PresentationError';
import { RaceDetailViewData } from '@/lib/view-data/races/RaceDetailViewData';
import { RacesService } from '@/lib/services/races/RacesService';
import { RaceDetailViewDataBuilder } from '@/lib/builders/view-data/RaceDetailViewDataBuilder';

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

/**
 * Race Detail Page Query
 * 
 * Fetches race detail data for the race detail page.
 * Returns Result<RaceDetailViewData, PresentationError>
 */
export class RaceDetailPageQuery implements PageQuery<RaceDetailViewData, RaceDetailPageQueryParams> {
  async execute(params: RaceDetailPageQueryParams): Promise<Result<RaceDetailViewData, PresentationError>> {
    // Manual wiring: Service creates its own dependencies
    const service = new RacesService();
    
    // Get race detail data
    const result = await service.getRaceDetail(params.raceId, params.driverId || '');
    
    if (result.isErr()) {
      return Result.err(mapToPresentationError(result.getError()));
    }
    
    // Transform to ViewData using builder
    const viewData = RaceDetailViewDataBuilder.build(result.unwrap());
    return Result.ok(viewData);
  }

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