import { DriversApiClient } from '@/lib/api/drivers/DriversApiClient';
import { Result } from '@/lib/contracts/Result';
import { Service, DomainError } from '@/lib/contracts/services/Service';
import { ConsoleErrorReporter } from '@/lib/infrastructure/logging/ConsoleErrorReporter';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
import type { DriverLeaderboardItemDTO } from '@/lib/types/generated/DriverLeaderboardItemDTO';
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
import { ApiError } from '@/lib/api/base/ApiError';

export interface DriverRankingsData {
  drivers: DriverLeaderboardItemDTO[];
}

export class DriverRankingsService implements Service {
  async getDriverRankings(): Promise<Result<DriverRankingsData, DomainError>> {
    try {
      const baseUrl = getWebsiteApiBaseUrl();
      const errorReporter = new ConsoleErrorReporter();
      const logger = new ConsoleLogger();
      
      const apiClient = new DriversApiClient(baseUrl, errorReporter, logger);
      const result = await apiClient.getLeaderboard();
      
      if (!result || !result.drivers) {
        return Result.err({ type: 'notFound', message: 'No driver rankings available' });
      }

      const data: DriverRankingsData = {
        drivers: result.drivers,
      };
      
      return Result.ok(data);
    } catch (error) {
      // Convert ApiError to DomainError
      if (error instanceof ApiError) {
        switch (error.type) {
          case 'NOT_FOUND':
            return Result.err({ type: 'notFound', message: error.message });
          case 'AUTH_ERROR':
            return Result.err({ type: 'unauthorized', message: error.message });
          case 'SERVER_ERROR':
            return Result.err({ type: 'serverError', message: error.message });
          case 'NETWORK_ERROR':
          case 'TIMEOUT_ERROR':
            return Result.err({ type: 'networkError', message: error.message });
          default:
            return Result.err({ type: 'unknown', message: error.message });
        }
      }
      
      // Handle non-ApiError cases
      if (error instanceof Error) {
        return Result.err({ type: 'unknown', message: error.message });
      }
      
      return Result.err({ type: 'unknown', message: 'Driver rankings fetch failed' });
    }
  }
}