/**
 * Test connection to ChainID 138 RPC endpoint
 */

import { initTatumSDK, verifyConnection } from './tatum-client';
import { CHAIN_ID, CHAIN_NAME, DEFAULT_RPC_URL } from './config';

async function main() {
  console.log('='.repeat(60));
  console.log(`Testing Connection to ${CHAIN_NAME}`);
  console.log(`ChainID: ${CHAIN_ID} (0x${CHAIN_ID.toString(16)})`);
  console.log(`RPC URL: ${DEFAULT_RPC_URL}`);
  console.log('='.repeat(60));
  console.log();
  
  try {
    // Initialize Tatum SDK
    console.log('Initializing Tatum SDK...');
    const tatum = await initTatumSDK({
      rpcUrl: DEFAULT_RPC_URL,
      verbose: true,
    });
    console.log('✓ Tatum SDK initialized\n');
    
    // Verify connection
    console.log('Verifying connection...');
    const connectionInfo = await verifyConnection(tatum);
    console.log('✓ Connection verified\n');
    
    // Display connection info
    console.log('Connection Information:');
    console.log('-'.repeat(60));
    console.log(`Chain ID:        ${connectionInfo.chainId} (${connectionInfo.chainIdHex})`);
    console.log(`Current Block:   ${connectionInfo.blockNumber}`);
    console.log(`Network Version: ${connectionInfo.netVersion}`);
    console.log(`Syncing:         ${connectionInfo.syncing}`);
    console.log('-'.repeat(60));
    console.log();
    
    // Test additional RPC calls
    console.log('Testing additional RPC calls...');
    
    // Get gas price
    const gasPrice = await tatum.rpc.request('eth_gasPrice', []);
    console.log(`✓ Gas Price: ${gasPrice}`);
    
    // Get peer count
    const peerCount = await tatum.rpc.request('net_peerCount', []);
    const peerCountDecimal = parseInt(peerCount as string, 16);
    console.log(`✓ Peer Count: ${peerCountDecimal}`);
    
    // Get latest block
    const latestBlock = await tatum.rpc.request('eth_getBlockByNumber', ['latest', false]);
    if (latestBlock && typeof latestBlock === 'object') {
      console.log(`✓ Latest Block: ${JSON.stringify(latestBlock, null, 2).substring(0, 200)}...`);
    }
    
    console.log();
    console.log('='.repeat(60));
    console.log('✓ All tests passed!');
    console.log('='.repeat(60));
    
  } catch (error) {
    console.error();
    console.error('='.repeat(60));
    console.error('✗ Connection test failed!');
    console.error('='.repeat(60));
    console.error();
    console.error('Error:', error instanceof Error ? error.message : String(error));
    console.error();
    console.error('Troubleshooting:');
    console.error('1. Ensure RPC node is running and accessible');
    console.error('2. Check RPC_URL environment variable');
    console.error('3. Verify firewall/network settings');
    console.error('4. Check node logs for errors');
    console.error();
    process.exit(1);
  }
}

main();

