/**
 * Tatum SDK client initialization for ChainID 138
 */

import { TatumSDK, Network, Ethereum, RpcNodeType } from '@tatumio/tatum';
import { getTatumConfig, CHAIN_ID, CHAIN_ID_HEX, NETWORK_CONFIG, TatumConfig } from './config';

/**
 * Initialize Tatum SDK for ChainID 138
 * 
 * Note: With custom RPC, only RPC calls are redirected to your node.
 * Tatum's cloud services (Notifications, Blockchain Data, etc.) won't work
 * on unsupported/private chains - only raw JSON-RPC will work.
 * 
 * @param config Optional configuration
 * @returns Initialized Tatum SDK instance
 */
export async function initTatumSDK(config?: TatumConfig) {
  const tatumConfig = getTatumConfig(config);
  
  // Option A: Simple initialization with custom RPC URL
  const tatum = await TatumSDK.init<Ethereum>({
    network: Network.ETHEREUM, // Use Ethereum network type for EVM compatibility
    rpcUrl: tatumConfig.rpcUrl,
    verbose: tatumConfig.verbose,
    // apiKey is optional and only needed for Tatum cloud features
    // With custom RPC, cloud features won't work anyway
    ...(tatumConfig.apiKey && { apiKey: tatumConfig.apiKey }),
  });
  
  return tatum;
}

/**
 * Initialize Tatum SDK with explicit node configuration
 * 
 * @param config Optional configuration
 * @returns Initialized Tatum SDK instance
 */
export async function initTatumSDKWithNodes(config?: TatumConfig) {
  const tatumConfig = getTatumConfig(config);
  
  // Option B: Explicit node configuration
  const tatum = await TatumSDK.init<Ethereum>({
    network: Network.ETHEREUM,
    rpc: {
      nodes: [
        {
          url: tatumConfig.rpcUrl!,
          type: RpcNodeType.NORMAL,
        },
      ],
    },
    verbose: tatumConfig.verbose,
    ...(tatumConfig.apiKey && { apiKey: tatumConfig.apiKey }),
  });
  
  return tatum;
}

/**
 * Verify connectivity and chain ID
 * 
 * @param tatum Tatum SDK instance
 * @returns Object with block number and chain ID
 */
export async function verifyConnection(tatum: Ethereum) {
  try {
    // Get current block number
    const blockNumberHex = await tatum.rpc.request('eth_blockNumber', []);
    const blockNumber = parseInt(blockNumberHex as string, 16);
    
    // Get chain ID
    const chainIdHex = await tatum.rpc.request('eth_chainId', []);
    const chainId = parseInt(chainIdHex as string, 16);
    
    // Verify chain ID
    if (chainId !== CHAIN_ID) {
      throw new Error(
        `Chain ID mismatch! Expected ${CHAIN_ID} (${CHAIN_ID_HEX}), got ${chainId} (${chainIdHex})`
      );
    }
    
    // Get network version
    const netVersion = await tatum.rpc.request('net_version', []);
    
    // Get sync status
    const syncing = await tatum.rpc.request('eth_syncing', []);
    
    return {
      blockNumber,
      blockNumberHex,
      chainId,
      chainIdHex,
      netVersion,
      syncing,
      networkConfig: NETWORK_CONFIG,
    };
  } catch (error) {
    throw new Error(`Failed to verify connection: ${error instanceof Error ? error.message : String(error)}`);
  }
}

