/**
 * Switch to ChainID 138 in MetaMask
 */

import { EthereumProvider, MetaMaskError } from './types';
import { CHAIN_ID_HEX } from './config';
import { getEthereumProvider } from './addNetwork';

/**
 * Switch to ChainID 138
 * @returns Promise that resolves when the network is switched
 */
export async function switchNetwork(): Promise<void> {
  const provider = getEthereumProvider();

  try {
    await provider.request({
      method: 'wallet_switchEthereumChain',
      params: [{ chainId: CHAIN_ID_HEX }],
    });
  } catch (error) {
    const metamaskError = error as MetaMaskError;
    
    // Error code 4902 means the chain is not added
    if (metamaskError.code === 4902) {
      throw new Error(
        'ChainID 138 is not added to MetaMask. Please add it first using addNetwork().'
      );
    }
    
    throw new Error(
      `Failed to switch network: ${metamaskError.message || 'Unknown error'}`
    );
  }
}

/**
 * Get the current chain ID
 */
export async function getCurrentChainId(): Promise<string> {
  const provider = getEthereumProvider();
  
  try {
    const chainId = await provider.request({ method: 'eth_chainId' }) as string;
    return chainId;
  } catch (error) {
    throw new Error(
      `Failed to get chain ID: ${(error as Error).message || 'Unknown error'}`
    );
  }
}

/**
 * Check if the current chain is ChainID 138
 */
export async function isOnChain138(): Promise<boolean> {
  try {
    const currentChainId = await getCurrentChainId();
    return currentChainId === CHAIN_ID_HEX;
  } catch {
    return false;
  }
}

