import { DriversApiClient } from '@/lib/api/drivers/DriversApiClient';
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
import { isProductionEnvironment } from '@/lib/config/env';
import { Result } from '@/lib/contracts/Result';
import type { Service } from '@/lib/contracts/services/Service';
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
import type { GetDriverProfileOutputDTO } from '@/lib/types/generated/GetDriverProfileOutputDTO';

type DriverProfilePageServiceError = 'notFound' | 'unauthorized' | 'serverError' | 'unknown';

/**
 * DriverProfilePageService
 * 
 * Service for the driver profile page.
 * Returns raw API DTOs. No ViewModels or UX logic.
 */
export class DriverProfilePageService implements Service {
  async getDriverProfile(driverId: string): Promise<Result<GetDriverProfileOutputDTO, DriverProfilePageServiceError>> {
    const logger = new ConsoleLogger();

    try {
      const baseUrl = getWebsiteApiBaseUrl();
      const errorReporter = new EnhancedErrorReporter(logger, {
        showUserNotifications: true,
        logToConsole: true,
        reportToExternal: isProductionEnvironment(),
      });

      const apiClient = new DriversApiClient(baseUrl, errorReporter, logger);
      const dto = await apiClient.getDriverProfile(driverId);

      if (!dto.currentDriver) {
        return Result.err('notFound');
      }

      return Result.ok(dto);
    } catch (error) {
      const errorAny = error as { statusCode?: number; message?: string };

      if (errorAny.statusCode === 401 || errorAny.message?.toLowerCase().includes('unauthorized')) {
        return Result.err('unauthorized');
      }

      if (errorAny.statusCode === 404 || errorAny.message?.toLowerCase().includes('not found')) {
        return Result.err('notFound');
      }

      logger.error('DriverProfilePageService failed', error instanceof Error ? error : undefined, { error: errorAny });

      if (errorAny.statusCode && errorAny.statusCode >= 500) {
        return Result.err('serverError');
      }

      return Result.err('unknown');
    }
  }
}