/**
 * Add token to MetaMask using EIP-747 (wallet_watchAsset)
 */

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

/**
 * Add an ERC-20 token to MetaMask
 * @param address - Token contract address
 * @param symbol - Token symbol
 * @param decimals - Token decimals
 * @param image - Optional token logo URL
 * @returns Promise that resolves when the token is added
 */
export async function addToken(
  address: string,
  symbol: string,
  decimals: number,
  image?: string
): Promise<void> {
  const provider = getEthereumProvider();

  // Validate address format
  if (!/^0x[a-fA-F0-9]{40}$/.test(address)) {
    throw new Error('Invalid token address format');
  }

  // Validate decimals
  if (decimals < 0 || decimals > 18) {
    throw new Error('Invalid decimals (must be between 0 and 18)');
  }

  const params: WatchAssetParameters = {
    type: 'ERC20',
    options: {
      address,
      symbol,
      decimals,
      ...(image && { image }),
    },
  };

  try {
    await provider.request({
      method: 'wallet_watchAsset',
      params,
    });
  } catch (error) {
    const metamaskError = error as MetaMaskError;
    throw new Error(
      `Failed to add token: ${metamaskError.message || 'Unknown error'}`
    );
  }
}

/**
 * Add token from token list entry
 * @param token - Token object with address, symbol, decimals, and optional logoURI
 */
export async function addTokenFromList(token: {
  address: string;
  symbol: string;
  decimals: number;
  logoURI?: string;
}): Promise<void> {
  return addToken(token.address, token.symbol, token.decimals, token.logoURI);
}

