/** 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[]
}

type WalletChainLike = WalletAddEthereumChainParams & {
  chainIdDecimal?: number
  oracles?: unknown
  shortName?: string
  infoURL?: string
  explorerApiUrl?: 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(
  chain: WalletChainLike,
  options?: { preferSingleRpc?: boolean },
): WalletAddEthereumChainParams {
  let rpcUrls = httpsOnly(chain.rpcUrls) ?? ['https://rpc-http-pub.d-bis.org']
  if (options?.preferSingleRpc && rpcUrls.length > 1) {
    rpcUrls = [rpcUrls[0]]
  }
  const out: WalletAddEthereumChainParams = {
    chainId: chain.chainId,
    chainName: chain.chainName,
    rpcUrls,
    nativeCurrency: chain.nativeCurrency,
  }
  const blockExplorerUrls = httpsOnly(chain.blockExplorerUrls)
  if (blockExplorerUrls) out.blockExplorerUrls = blockExplorerUrls
  const iconUrls = httpsOnly(chain.iconUrls)
  if (iconUrls) out.iconUrls = iconUrls
  return out
}
