import { ref } from 'vue'
import { HUB_URL } from 'src/config/hub'

/**
 * Reusable address search composable (autosuggest RQA).
 * Cherche via le hub `/rpc/search_addresses` (Postgres rqa_addresses, trigram) — FIABLE et joignable en dev ET prod
 * (le proxy /hub ajoute le jeton). Remplace l'ancien `/api/method/search_address` (ERPNext) qui échouait (403/perm).
 */
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(`${HUB_URL}/rpc/search_addresses`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ search_term: q, result_limit: 8 }) })
        const data = await res.json()
        addrResults.value = Array.isArray(data) ? data : (data.results || data.message?.results || []) // /rpc renvoie un tableau direct
      } 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 }
}
