import type { NetworkEntry } from '../config/networks';

/** EIP-3085 fields accepted by MetaMask `wallet_addEthereumChain` (strict subset). */
export type WalletAddEthereumChainParams = {
  chainId: string;
  chainName: string;
  rpcUrls: string[];
  nativeCurrency: { name: string; symbol: string; decimals: number };
  blockExplorerUrls?: string[];
  iconUrls?: string[];
};

function httpsOnly(urls: string[] | undefined): string[] | undefined {
  if (!urls?.length) return undefined;
  const filtered = urls.filter((url) => typeof url === 'string' && url.startsWith('https://'));
  return filtered.length > 0 ? filtered : undefined;
}

/** Strip `chainIdDecimal`, `oracles`, and other keys MetaMask rejects. */
export function toWalletAddEthereumChainParams(
  network: Pick<
    NetworkEntry,
    'chainId' | 'chainName' | 'rpcUrls' | 'nativeCurrency' | 'blockExplorerUrls' | 'iconUrls'
  >
): WalletAddEthereumChainParams {
  const rpcUrls = httpsOnly(network.rpcUrls) ?? ['https://rpc-http-pub.d-bis.org'];
  const out: WalletAddEthereumChainParams = {
    chainId: network.chainId,
    chainName: network.chainName,
    rpcUrls,
    nativeCurrency: network.nativeCurrency,
  };
  const blockExplorerUrls = httpsOnly(network.blockExplorerUrls);
  if (blockExplorerUrls) out.blockExplorerUrls = blockExplorerUrls;
  const iconUrls = httpsOnly(network.iconUrls);
  if (iconUrls) out.iconUrls = iconUrls;
  return out;
}
