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 { DriversLeaderboardDTO } from '@/lib/types/generated/DriversLeaderboardDTO';

type DriversPageServiceError = 'notFound' | 'serverError' | 'unknown';

/**
 * DriversPageService
 * 
 * Service for the drivers listing page.
 * Returns raw API DTOs. No ViewModels or UX logic.
 */
export class DriversPageService implements Service {
  async getLeaderboard(): Promise<Result<DriversLeaderboardDTO, DriversPageServiceError>> {
    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 result = await apiClient.getLeaderboard();

      if (!result || !result.drivers) {
        return Result.err('notFound');
      }

      // Transform to the expected DTO format
      const dto: DriversLeaderboardDTO = {
        drivers: result.drivers,
        totalRaces: result.drivers.reduce((sum, driver) => sum + driver.racesCompleted, 0),
        totalWins: result.drivers.reduce((sum, driver) => sum + driver.wins, 0),
        activeCount: result.drivers.filter(driver => driver.isActive).length,
      };

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

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

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

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