import { registerAs } from '@nestjs/config';

/**
 * 区块链配置
 *
 * 支持主网和测试网切换，通过 NETWORK_MODE 环境变量控制:
 * - NETWORK_MODE=mainnet (默认): 使用主网配置
 * - NETWORK_MODE=testnet: 使用测试网配置
 *
 * 测试网配置:
 * - BSC Testnet: Chain ID 97, 水龙头: https://testnet.bnbchain.org/faucet-smart
 * - KAVA Testnet: Chain ID 2221, 水龙头: https://faucet.kava.io
 */
export default registerAs('blockchain', () => {
  const networkMode = process.env.NETWORK_MODE || 'mainnet';
  const isTestnet = networkMode === 'testnet';

  return {
    // 网络模式
    networkMode,
    isTestnet,

    // 通用配置
    scanIntervalMs: parseInt(process.env.BLOCK_SCAN_INTERVAL_MS || '5000', 10),
    confirmationsRequired: parseInt(process.env.BLOCK_CONFIRMATIONS_REQUIRED || (isTestnet ? '3' : '12'), 10),
    scanBatchSize: parseInt(process.env.BLOCK_SCAN_BATCH_SIZE || '100', 10),

    // KAVA 配置
    kava: isTestnet
      ? {
          // KAVA Testnet
          rpcUrl: process.env.KAVA_RPC_URL || 'https://evm.testnet.kava.io',
          // 逗号分隔的多个 RPC URL，用于故障转移（可选，不配置则仅使用 rpcUrl）
          rpcUrls: process.env.KAVA_RPC_URLS || '',
          chainId: parseInt(process.env.KAVA_CHAIN_ID || '2221', 10),
          // 测试网 USDT 合约 (自定义部署的 TestUSDT)
          usdtContract: process.env.KAVA_USDT_CONTRACT || '0xc12f6A4A7Fd0965085B044A67a39CcA2ff7fe0dF',
          confirmations: parseInt(process.env.KAVA_CONFIRMATIONS || '3', 10),
        }
      : {
          // KAVA Mainnet
          rpcUrl: process.env.KAVA_RPC_URL || 'https://evm.kava.io',
          // 逗号分隔的多个 RPC URL，用于故障转移（可选，不配置则仅使用 rpcUrl）
          rpcUrls: process.env.KAVA_RPC_URLS || '',
          chainId: parseInt(process.env.KAVA_CHAIN_ID || '2222', 10),
          // dUSDT (绿积分) 合约地址 - Durian USDT, 精度6位
          usdtContract: process.env.KAVA_USDT_CONTRACT || '0xA9F3A35dBa8699c8C681D8db03F0c1A8CEB9D7c3',
          confirmations: parseInt(process.env.KAVA_CONFIRMATIONS || '12', 10),
        },

    // BSC 配置
    bsc: isTestnet
      ? {
          // BSC Testnet (BNB Smart Chain Testnet)
          rpcUrl: process.env.BSC_RPC_URL || 'https://data-seed-prebsc-1-s1.binance.org:8545',
          rpcUrls: process.env.BSC_RPC_URLS || '',
          chainId: parseInt(process.env.BSC_CHAIN_ID || '97', 10),
          // BSC Testnet 官方测试 USDT 合约
          usdtContract: process.env.BSC_USDT_CONTRACT || '0x337610d27c682E347C9cD60BD4b3b107C9d34dDd',
          confirmations: parseInt(process.env.BSC_CONFIRMATIONS || '3', 10),
        }
      : {
          // BSC Mainnet
          rpcUrl: process.env.BSC_RPC_URL || 'https://bsc-dataseed.binance.org',
          rpcUrls: process.env.BSC_RPC_URLS || '',
          chainId: parseInt(process.env.BSC_CHAIN_ID || '56', 10),
          usdtContract: process.env.BSC_USDT_CONTRACT || '0x55d398326f99059fF775485246999027B3197955',
          confirmations: parseInt(process.env.BSC_CONFIRMATIONS || '15', 10),
        },
  };
});
