import { useEffect } from 'react'
import { useQuery } from '@tanstack/react-query'
import { setContractAddress } from '@/config/contractRegistry'

interface ContractEntry {
  name: string
  chain_id: number
  address: string
}

async function fetchContracts(): Promise<ContractEntry[]> {
  try {
    const res = await fetch('/api/contracts')
    if (!res.ok) return []
    const data = await res.json()
    return data.contracts ?? []
  } catch {
    return []
  }
}

/**
 * 从后端 /api/contracts 获取所有合约地址并写入 registry。
 * 在 rootContainer 靠近根部调用一次即可，所有页面共享同一份缓存。
 */
export function useContractRegistry() {
  const { data } = useQuery({
    queryKey: ['contract-registry'],
    queryFn: fetchContracts,
    staleTime: 5 * 60 * 1000,
    gcTime: 30 * 60 * 1000,
  })

  useEffect(() => {
    if (!data) return
    for (const c of data) {
      if (c.address) setContractAddress(c.name, c.chain_id, c.address)
    }
  }, [data])
}
