/**
 * Deploy TestUSDT to BSC Testnet
 *
 * Usage:
 *   npx ts-node scripts/deploy-test-usdt.ts <PRIVATE_KEY>
 *
 * Example:
 *   npx ts-node scripts/deploy-test-usdt.ts 0xabc123...
 *
 * Get BSC Testnet tBNB from: https://www.bnbchain.org/en/testnet-faucet
 */

import { ethers, ContractFactory } from 'ethers';

// BSC Testnet 配置
const BSC_TESTNET_RPC = 'https://data-seed-prebsc-1-s1.binance.org:8545';
const BSC_TESTNET_CHAIN_ID = 97;

// TestUSDT 合约 ABI 和 Bytecode
const CONTRACT_ABI = [
  'constructor()',
  'function name() view returns (string)',
  'function symbol() view returns (string)',
  'function decimals() view returns (uint8)',
  'function totalSupply() view returns (uint256)',
  'function balanceOf(address) view returns (uint256)',
  'function transfer(address to, uint256 amount) returns (bool)',
  'function approve(address spender, uint256 amount) returns (bool)',
  'function allowance(address owner, address spender) view returns (uint256)',
  'function transferFrom(address from, address to, uint256 amount) returns (bool)',
  'function mint(uint256 amount)',
  'function mintUsdt(uint256 usdtAmount)',
  'function mintTo(address to, uint256 amount)',
  'function faucet()',
  'function owner() view returns (address)',
  'event Transfer(address indexed from, address indexed to, uint256 value)',
  'event Approval(address indexed owner, address indexed spender, uint256 value)',
];

// 编译后的 bytecode (TestUSDT_Flat.sol)
const CONTRACT_BYTECODE =
  '[encoded data, 8281 characters]';

async function main() {
  const privateKey = process.argv[2];

  if (!privateKey) {
    console.error(`
❌ Usage: npx ts-node scripts/deploy-test-usdt.ts <PRIVATE_KEY>

Steps:
1. Get tBNB from https://www.bnbchain.org/en/testnet-faucet
2. Export your private key from MetaMask
3. Run: npx ts-node scripts/deploy-test-usdt.ts 0xYourPrivateKey
    `);
    process.exit(1);
  }

  console.log('🚀 Deploying TestUSDT to BSC Testnet...\n');

  // 连接到 BSC Testnet
  const provider = new ethers.JsonRpcProvider(BSC_TESTNET_RPC, {
    chainId: BSC_TESTNET_CHAIN_ID,
    name: 'bsc-testnet',
  });

  // 创建钱包
  const wallet = new ethers.Wallet(privateKey, provider);
  console.log(`📍 Deployer address: ${wallet.address}`);

  // 检查余额
  const balance = await provider.getBalance(wallet.address);
  console.log(`💰 Balance: ${ethers.formatEther(balance)} tBNB`);

  if (balance < ethers.parseEther('0.01')) {
    console.error('\n❌ Insufficient tBNB. Get some from https://www.bnbchain.org/en/testnet-faucet');
    process.exit(1);
  }

  // 部署合约
  console.log('\n📦 Deploying contract...');
  const factory = new ContractFactory(CONTRACT_ABI, CONTRACT_BYTECODE, wallet);
  const contract = await factory.deploy();

  console.log(`⏳ Waiting for confirmation...`);
  console.log(`   Transaction: https://testnet.bscscan.com/tx/${contract.deploymentTransaction()?.hash}`);

  await contract.waitForDeployment();
  const contractAddress = await contract.getAddress();

  console.log(`
✅ TestUSDT deployed successfully!

📋 Contract Address: ${contractAddress}
🔗 BSCScan: https://testnet.bscscan.com/address/${contractAddress}

Next steps:
1. Update .env: BSC_USDT_CONTRACT=${contractAddress}
2. Call faucet() to mint 10,000 USDT for testing
3. Or call mintUsdt(100000) to mint 100,000 USDT
  `);
}

main().catch((error) => {
  console.error('❌ Deployment failed:', error.message);
  process.exit(1);
});
