import { Injectable, Logger } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import { firstValueFrom } from 'rxjs';
import { IReferralServiceClient } from '../../domain/services/leaderboard-calculation.service';

/**
 * Referral Service 客户端实现
 *
 * 从推荐服务获取团队统计数据
 */
@Injectable()
export class ReferralServiceClient implements IReferralServiceClient {
  private readonly logger = new Logger(ReferralServiceClient.name);
  private readonly baseUrl: string;

  constructor(
    private readonly httpService: HttpService,
    private readonly configService: ConfigService,
  ) {
    this.baseUrl = this.configService.get<string>('REFERRAL_SERVICE_URL', 'http://localhost:3004');
  }

  async getTeamStatisticsForLeaderboard(params: {
    periodStartAt: Date;
    periodEndAt: Date;
    limit: number;
  }): Promise<Array<{
    userId: bigint;
    totalTeamPlanting: number;
    maxDirectTeamPlanting: number;
    effectiveScore: number;
  }>> {
    try {
      const response = await firstValueFrom(
        this.httpService.get(`${this.baseUrl}/api/team-statistics/leaderboard`, {
          params: {
            periodStartAt: params.periodStartAt.toISOString(),
            periodEndAt: params.periodEndAt.toISOString(),
            limit: params.limit,
          },
        }),
      );

      return (response.data.data || []).map((item: any) => ({
        userId: BigInt(item.userId),
        totalTeamPlanting: item.totalTeamPlanting,
        maxDirectTeamPlanting: item.maxDirectTeamPlanting,
        effectiveScore: item.effectiveScore,
      }));
    } catch (error) {
      this.logger.error('获取团队统计数据失败', error);
      // 返回空数组，让系统继续运行
      return [];
    }
  }
}
