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

/**
 * Wallet Service 客户端
 * 跨服务调用 wallet-service 的冻结/解冻/转账接口
 */
@Injectable()
export class WalletServiceClient {
  private readonly logger = new Logger(WalletServiceClient.name);
  private readonly baseUrl: string;

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

  /**
   * 冻结买方资金
   */
  async freezePayment(params: {
    accountSequence: string;
    amount: string;
    transferOrderNo: string;
    reason: string;
  }): Promise<{ freezeId: string }> {
    const url = `${this.baseUrl}/api/v1/internal/wallet/freeze`;
    this.logger.log(`[WALLET] Freezing ${params.amount} USDT for ${params.accountSequence}`);

    const { data } = await firstValueFrom(
      this.httpService.post(url, params),
    );
    return data;
  }

  /**
   * 解冻买方资金（补偿操作）
   */
  async unfreezePayment(params: {
    accountSequence: string;
    freezeId: string;
    transferOrderNo: string;
    reason: string;
  }): Promise<void> {
    const url = `${this.baseUrl}/api/v1/internal/wallet/unfreeze`;
    this.logger.log(`[WALLET] Unfreezing for ${params.accountSequence}`);

    await firstValueFrom(this.httpService.post(url, params));
  }

  /**
   * 结算转让资金
   * 从买方冻结金额 → 卖方实收 + 平台手续费
   */
  async settleTransferPayment(params: {
    buyerAccountSequence: string;
    sellerAccountSequence: string;
    freezeId: string;
    sellerReceiveAmount: string;
    platformFeeAmount: string;
    transferOrderNo: string;
  }): Promise<void> {
    const url = `${this.baseUrl}/api/v1/internal/wallet/settle-transfer`;
    this.logger.log(`[WALLET] Settling transfer ${params.transferOrderNo}`);

    await firstValueFrom(this.httpService.post(url, params));
  }

  /**
   * 查询账户余额
   */
  async getBalance(accountSequence: string): Promise<{ available: string; frozen: string }> {
    const url = `${this.baseUrl}/api/v1/internal/wallet/balance/${accountSequence}`;
    const { data } = await firstValueFrom(this.httpService.get(url));
    return data;
  }
}
