import { Result } from '@/lib/contracts/Result';
import { DriversPageService } from '@/lib/services/drivers/DriversPageService';
import { DriversViewDataBuilder } from '@/lib/builders/view-data/DriversViewDataBuilder';
import type { DriversViewData } from '@/lib/types/view-data/DriversViewData';

/**
 * DriversPageQuery
 *
 * Server-side data fetcher for the drivers listing page.
 * Returns Result<ViewData, PresentationError>
 * Uses Service for data access and ViewDataBuilder for transformation.
 */
export class DriversPageQuery {
  /**
   * Execute the drivers page query
   *
   * @returns Result with ViewData or error
   */
  static async execute(): Promise<Result<DriversViewData, string>> {
    try {
      // Manual wiring: construct dependencies explicitly
      const service = new DriversPageService();

      const result = await service.getLeaderboard();

      if (result.isErr()) {
        const error = result.getError();

        if (error === 'notFound') {
          return Result.err('NotFound');
        }

        return Result.err('Error');
      }

      // Build ViewData from DTO
      const dto = result.unwrap();
      const viewData = DriversViewDataBuilder.build(dto);
      return Result.ok(viewData);

    } catch (error) {
      console.error('DriversPageQuery failed:', error);
      return Result.err('Error');
    }
  }
}