'use client'

import { useEffect } from 'react'
import { useQuery } from '@tanstack/react-query'
import { fetchContracts } from '@/lib/api/contracts'
import { setContractAddressDynamic } from '@/lib/contracts/registry'

/**
 * Fetches contract addresses from the backend and populates the dynamic registry.
 * Call once near the app root (e.g., inside Providers or AppContext).
 * All existing getContractAddress() callers automatically see updated values.
 */
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) setContractAddressDynamic(c.name, c.chain_id, c.address)
    }
  }, [data])
}
