import { Result } from '@/lib/contracts/Result';
import { DriverProfilePageService } from '@/lib/services/drivers/DriverProfilePageService';
import { DriverProfileViewDataBuilder } from '@/lib/builders/view-data/DriverProfileViewDataBuilder';
import type { DriverProfileViewData } from '@/lib/types/view-data/DriverProfileViewData';

/**
 * DriverProfilePageQuery
 *
 * Server-side data fetcher for the driver profile page.
 * Returns Result<ViewData, PresentationError>
 * Uses Service for data access and ViewDataBuilder for transformation.
 */
export class DriverProfilePageQuery {
  /**
   * Execute the driver profile page query
   *
   * @param driverId - The driver ID to fetch profile for
   * @returns Result with ViewData or error
   */
  static async execute(driverId: string | null): Promise<Result<DriverProfileViewData, string>> {
    if (!driverId) {
      return Result.err('NotFound');
    }

    try {
      // Manual wiring: construct dependencies explicitly
      const service = new DriverProfilePageService();

      const result = await service.getDriverProfile(driverId);

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

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

        if (error === 'unauthorized') {
          return Result.err('Unauthorized');
        }

        return Result.err('Error');
      }

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

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