import { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { Result } from '@/lib/contracts/Result';
import { DriverRankingsViewDataBuilder } from '@/lib/builders/view-data/DriverRankingsViewDataBuilder';
import type { DriverRankingsViewData } from '@/lib/view-data/DriverRankingsViewData';
import { DriverRankingsService } from '@/lib/services/leaderboards/DriverRankingsService';
import { mapToPresentationError, type PresentationError } from '@/lib/contracts/page-queries/PresentationError';

/**
 * Driver Rankings page query
 * Returns Result<DriverRankingsViewData, PresentationError>
 * No DI container usage - constructs dependencies explicitly
 */
export class DriverRankingsPageQuery implements PageQuery<DriverRankingsViewData, void, PresentationError> {
  async execute(): Promise<Result<DriverRankingsViewData, PresentationError>> {
    // Manual wiring: Service creates its own dependencies
    const service = new DriverRankingsService();
    
    // Fetch data using service
    const serviceResult = await service.getDriverRankings();
    
    if (serviceResult.isErr()) {
      // Map domain errors to presentation errors
      return Result.err(mapToPresentationError(serviceResult.getError()));
    }

    // Transform to ViewData using builder
    const apiDto = serviceResult.unwrap();
    const viewData = DriverRankingsViewDataBuilder.build(apiDto.drivers);
    return Result.ok(viewData);
  }

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