/**
 * 热钱包余额缓存服务
 * [2026-01-07] 新增：从 Redis 读取热钱包余额（由 blockchain-service 写入）
 *
 * Redis Key 格式：
 *   - hot_wallet:dusdt_balance:{chainType} - dUSDT 余额
 *   - hot_wallet:native_balance:{chainType} - 原生代币余额 (KAVA/BNB)
 *
 * 回滚方式：删除此文件，并从 redis.module.ts 中移除注册
 */
import { Injectable, Logger } from '@nestjs/common';
import { RedisService } from './redis.service';

/**
 * 热钱包余额响应
 */
export interface HotWalletBalanceResponse {
  /** dUSDT (绿积分) 余额 */
  dusdtBalance: string | null;
  /** 原生代币余额 (KAVA) */
  nativeBalance: string | null;
  /** 链类型 */
  chainType: string;
  /** 是否有效（数据是否在 TTL 内） */
  isValid: boolean;
}

@Injectable()
export class HotWalletBalanceCacheService {
  private readonly logger = new Logger(HotWalletBalanceCacheService.name);

  // Redis key 前缀（与 blockchain-service 保持一致）
  private readonly REDIS_KEY_PREFIX_DUSDT = 'hot_wallet:dusdt_balance:';
  private readonly REDIS_KEY_PREFIX_NATIVE = 'hot_wallet:native_balance:';

  constructor(private readonly redisService: RedisService) {}

  /**
   * 获取指定链的热钱包余额
   * @param chainType 链类型 (KAVA, BSC)
   */
  async getHotWalletBalance(chainType: string = 'KAVA'): Promise<HotWalletBalanceResponse> {
    try {
      const dusdtKey = `${this.REDIS_KEY_PREFIX_DUSDT}${chainType}`;
      const nativeKey = `${this.REDIS_KEY_PREFIX_NATIVE}${chainType}`;

      const [dusdtBalance, nativeBalance] = await Promise.all([
        this.redisService.get(dusdtKey),
        this.redisService.get(nativeKey),
      ]);

      const isValid = dusdtBalance !== null || nativeBalance !== null;

      this.logger.debug(
        `[getHotWalletBalance] ${chainType}: dUSDT=${dusdtBalance}, native=${nativeBalance}, valid=${isValid}`,
      );

      return {
        dusdtBalance,
        nativeBalance,
        chainType,
        isValid,
      };
    } catch (error) {
      this.logger.error(`[getHotWalletBalance] Failed to get balance for ${chainType}`, error);
      return {
        dusdtBalance: null,
        nativeBalance: null,
        chainType,
        isValid: false,
      };
    }
  }

  /**
   * 获取所有链的热钱包余额
   */
  async getAllHotWalletBalances(): Promise<HotWalletBalanceResponse[]> {
    const chainTypes = ['KAVA', 'BSC'];
    const results: HotWalletBalanceResponse[] = [];

    for (const chainType of chainTypes) {
      const balance = await this.getHotWalletBalance(chainType);
      results.push(balance);
    }

    return results;
  }
}
