import { Result } from '@/lib/contracts/Result';
import { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { PresentationError, mapToPresentationError } from '@/lib/contracts/page-queries/PresentationError';
import { RaceStewardingViewData } from '@/lib/view-data/races/RaceStewardingViewData';
import { RaceStewardingService } from '@/lib/services/races/RaceStewardingService';
import { RaceStewardingViewDataBuilder } from '@/lib/builders/view-data/RaceStewardingViewDataBuilder';

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

/**
 * Race Stewarding Page Query
 * 
 * Fetches race stewarding data for the stewarding page.
 * Returns Result<RaceStewardingViewData, PresentationError>
 */
export class RaceStewardingPageQuery implements PageQuery<RaceStewardingViewData, RaceStewardingPageQueryParams> {
  async execute(params: RaceStewardingPageQueryParams): Promise<Result<RaceStewardingViewData, PresentationError>> {
    // Manual wiring: Service creates its own dependencies
    const service = new RaceStewardingService();
    
    // Get race stewarding data
    const result = await service.getRaceStewarding(params.raceId);
    
    if (result.isErr()) {
      return Result.err(mapToPresentationError(result.getError()));
    }
    
    // Transform to ViewData using builder
    const viewData = RaceStewardingViewDataBuilder.build(result.unwrap());
    return Result.ok(viewData);
  }

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