/**
 * API Conformité des adresses — appelle targo-hub /address/conformity/*.
 * Source de vérité : Service Location (lien AQ local rqa_addresses). Voir services/targo-hub/lib/address-conformity.js.
 */
import { HUB_URL as HUB } from 'src/config/hub'

async function jget (path) {
  const r = await fetch(HUB + path)
  if (!r.ok) throw new Error('Address API ' + r.status)
  return r.json()
}
async function jpost (path, body) {
  const r = await fetch(HUB + path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })
  if (!r.ok) throw new Error('Address API ' + r.status)
  return r.json()
}

export const conformityStats = () => jget('/address/conformity/stats')
export const conformityList = (p) => jget('/address/conformity/list?' + new URLSearchParams(p).toString())
export const conformityCandidates = (q) => jget('/address/conformity/candidates?q=' + encodeURIComponent(q))
// action: approve | correct | gps | reject (+ aq_address_id/linked_address/latitude/longitude selon l'action)
export const conformityResolve = (body) => jpost('/address/conformity/resolve', body)

// ── Registre des campings (géoloc de remplacement fixe par camping) ──
export const campingsList = () => jget('/address/conformity/campings')
export const campingsUpsert = (body) => jpost('/address/conformity/campings', body) // {keyword,name,address,latitude,longitude}
export const campingsApply = () => jpost('/address/conformity/campings/apply', {})
// Dernier repli : placer les unmatched restants au centre du code postal (sinon ville) → statut 'area'
export const conformityApplyArea = () => jpost('/address/conformity/apply-area', {})

// Géocodage INVERSE (coord → adresse) via notre RQA locale (plus de Nominatim externe).
export const reverse = (lat, lon) => jget('/address/reverse?lat=' + encodeURIComponent(lat) + '&lon=' + encodeURIComponent(lon))
