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

/**
 * 月度收益信息接口
 */
export interface MonthlyEarningsInfo {
  accountSequence: string;
  monthlySettleableUsdt: number;
  monthlyShareUsdt: number;
  monthlyProvinceTeamUsdt: number;
  monthlyCityTeamUsdt: number;
  monthlyTotalUsdt: number;
}

/**
 * Reward Service HTTP 客户端
 * 用于从 reward-service 获取收益信息
 */
@Injectable()
export class RewardServiceClient implements OnModuleInit {
  private readonly logger = new Logger(RewardServiceClient.name);
  private httpClient: AxiosInstance;
  private readonly baseUrl: string;
  private readonly enabled: boolean;

  constructor(private readonly configService: ConfigService) {
    this.baseUrl = this.configService.get<string>('REWARD_SERVICE_URL') || 'http://rwa-reward-service:3000';
    this.enabled = this.configService.get<boolean>('REWARD_SERVICE_ENABLED') !== false;
  }

  onModuleInit() {
    this.httpClient = axios.create({
      baseURL: this.baseUrl,
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json',
      },
    });

    this.logger.log(`[INIT] RewardServiceClient initialized: ${this.baseUrl}, enabled: ${this.enabled}`);
  }

  /**
   * 批量获取月度收益
   *
   * @param accountSequences 账户序列号列表
   * @param month 月份，格式 YYYY-MM
   * @param rightTypes 可选，过滤权益类型
   */
  async batchGetMonthlyEarnings(
    accountSequences: string[],
    month: string,
    rightTypes?: string[],
  ): Promise<Map<string, MonthlyEarningsInfo>> {
    const result = new Map<string, MonthlyEarningsInfo>();

    if (!this.enabled || accountSequences.length === 0) {
      return result;
    }

    try {
      this.logger.debug(`[HTTP] POST /internal/monthly-earnings/batch - ${accountSequences.length} accounts, month=${month}`);

      const response = await this.httpClient.post<MonthlyEarningsInfo[]>(
        `/api/v1/internal/monthly-earnings/batch`,
        {
          accountSequences,
          month,
          rightTypes,
        },
      );

      // 处理响应
      const data = response.data;
      if (data && Array.isArray(data)) {
        for (const item of data) {
          result.set(item.accountSequence, item);
        }
      }

      this.logger.debug(`[HTTP] Got ${result.size} monthly earnings records`);
    } catch (error) {
      this.logger.error(`[HTTP] Failed to batch get monthly earnings:`, error);
    }

    return result;
  }

  /**
   * 获取单个账户的月度收益
   */
  async getMonthlyEarnings(
    accountSequence: string,
    month: string,
    rightTypes?: string[],
  ): Promise<MonthlyEarningsInfo | null> {
    const result = await this.batchGetMonthlyEarnings([accountSequence], month, rightTypes);
    return result.get(accountSequence) || null;
  }
}
