import { TeamsApiClient } from '@/lib/api/teams/TeamsApiClient';
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 { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
import { ApiError } from '@/lib/api/base/ApiError';
import type { GetTeamsLeaderboardOutputDTO } from '@/lib/types/generated/GetTeamsLeaderboardOutputDTO';

export class TeamRankingsService implements Service {
  async getTeamRankings(): Promise<Result<GetTeamsLeaderboardOutputDTO, DomainError>> {
    try {
      const baseUrl = getWebsiteApiBaseUrl();
      const errorReporter = new ConsoleErrorReporter();
      const logger = new ConsoleLogger();

      const teamsApiClient = new TeamsApiClient(baseUrl, errorReporter, logger);

      const teamResult = await teamsApiClient.getLeaderboard();

      if (!teamResult) {
        return Result.err({ type: 'notFound', message: 'No team leaderboard data available' });
      }

      return Result.ok(teamResult);
    } catch (error) {
      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 });
        }
      }

      if (error instanceof Error) {
        return Result.err({ type: 'unknown', message: error.message });
      }

      return Result.err({ type: 'unknown', message: 'Team rankings fetch failed' });
    }
  }
}
