/**
 * Dynamic contract address registry.
 * Populated from /api/contracts at runtime; falls back to static config.
 * Module-level store — safe because addresses are the same across all renders.
 */
const dynamicRegistry = new Map<string, `0x${string}`>()

export function setContractAddressDynamic(name: string, chainId: number, address: string) {
  if (address && address.startsWith('0x')) {
    dynamicRegistry.set(`${name}:${chainId}`, address as `0x${string}`)
  }
}

export function getDynamicOverride(name: string, chainId: number): `0x${string}` | undefined {
  return dynamicRegistry.get(`${name}:${chainId}`)
}

/**
 * 按名称搜索，忽略 chainId（当 token 的 chainId=0 即 DB 未配置时使用）
 * 返回第一个匹配的 { address, chainId }
 */
export function getDynamicOverrideByName(name: string): { address: `0x${string}`; chainId: number } | undefined {
  for (const [key, value] of dynamicRegistry) {
    if (key.startsWith(`${name}:`)) {
      const chainId = parseInt(key.split(':')[1], 10)
      return { address: value, chainId }
    }
  }
  return undefined
}
