import { ref } from 'vue'

/**
 * Reusable address search composable.
 * Searches ERPNext `search_address` whitelisted method with debounce.
 */
export function useAddressSearch () {
  const addrResults = ref([])
  const addrLoading = ref(false)
  let addrDebounce = null

  function searchAddr (q) {
    clearTimeout(addrDebounce)
    if (!q || q.length < 3) { addrResults.value = []; return }
    addrLoading.value = true
    addrDebounce = setTimeout(async () => {
      try {
        const res = await fetch(`/api/method/search_address?q=${encodeURIComponent(q)}`, { credentials: 'include' })
        const data = await res.json()
        addrResults.value = data.results || data.message?.results || []
      } catch { addrResults.value = [] }
      addrLoading.value = false
    }, 300)
  }

  function selectAddr (addr, target) {
    if (!target) { addrResults.value = []; return }
    target.address = addr.address_full
    if (addr.latitude) target.latitude = parseFloat(addr.latitude)
    if (addr.longitude) target.longitude = parseFloat(addr.longitude)
    if (addr.ville) target.ville = addr.ville
    if (addr.code_postal) target.code_postal = addr.code_postal
    addrResults.value = []
  }

  return { addrResults, addrLoading, searchAddr, selectAddr }
}
