/**
 * 推荐链预种统计代理服务
 * [2026-03-02] 新增：通过内部 HTTP 调用 referral-service 获取预种统计数据
 *
 * === 架构 ===
 * admin-web → admin-service (本服务) → referral-service /internal/referral/pre-planting-stats/*
 * 复用现有 PrePlantingProxyService 的 axios 代理模式
 */

import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios, { AxiosInstance } from 'axios';

export interface PrePlantingStats {
  selfPrePlantingPortions: number;
  teamPrePlantingPortions: number;
}

@Injectable()
export class ReferralProxyService {
  private readonly logger = new Logger(ReferralProxyService.name);
  private readonly httpClient: AxiosInstance;

  constructor(private readonly configService: ConfigService) {
    const referralServiceUrl = this.configService.get<string>(
      'REFERRAL_SERVICE_URL',
      'http://rwa-referral-service:3004',
    );

    this.httpClient = axios.create({
      baseURL: referralServiceUrl,
      timeout: 30000,
    });

    this.logger.log(
      `ReferralProxyService initialized, referral-service URL: ${referralServiceUrl}`,
    );
  }

  /**
   * 获取单个用户的预种统计（个人 + 团队预种份数）
   */
  async getPrePlantingStats(accountSequence: string): Promise<PrePlantingStats> {
    try {
      const url = `/api/v1/internal/referral/pre-planting-stats/${accountSequence}`;
      this.logger.debug(`[getPrePlantingStats] 请求: ${url}`);
      const response = await this.httpClient.get(url);
      return {
        selfPrePlantingPortions: response.data?.selfPrePlantingPortions ?? 0,
        teamPrePlantingPortions: response.data?.teamPrePlantingPortions ?? 0,
      };
    } catch (error) {
      this.logger.error(`[getPrePlantingStats] 失败 (${accountSequence}): ${error.message}`);
      return { selfPrePlantingPortions: 0, teamPrePlantingPortions: 0 };
    }
  }

  /**
   * 批量获取多个用户的预种统计
   */
  async batchGetPrePlantingStats(
    accountSequences: string[],
  ): Promise<Record<string, PrePlantingStats>> {
    if (accountSequences.length === 0) {
      return {};
    }

    try {
      const url = '/api/v1/internal/referral/pre-planting-stats/batch';
      this.logger.debug(`[batchGetPrePlantingStats] 请求: ${url}, 数量: ${accountSequences.length}`);
      const response = await this.httpClient.post(url, { accountSequences });
      return response.data ?? {};
    } catch (error) {
      this.logger.error(`[batchGetPrePlantingStats] 失败: ${error.message}`);
      // 返回所有用户的零值默认
      const defaults: Record<string, PrePlantingStats> = {};
      for (const seq of accountSequences) {
        defaults[seq] = { selfPrePlantingPortions: 0, teamPrePlantingPortions: 0 };
      }
      return defaults;
    }
  }
}
