import type { LatLng, NominatimItem } from '../model/types'

export async function reverseGeocode(pos: LatLng): Promise<string | null> {
  const url = new URL('https://nominatim.openstreetmap.org/reverse')
  url.searchParams.set('format', 'jsonv2')
  url.searchParams.set('lat', String(pos.lat))
  url.searchParams.set('lon', String(pos.lng))
  url.searchParams.set('accept-language', 'ru')
  const res = await fetch(url.toString(), { headers: { 'User-Agent': 'craftshop-demo' } })
  if (!res.ok) return null
  const data = (await res.json()) as { display_name?: string }
  return data.display_name ? String(data.display_name) : null
}

export async function searchPlaces(q: string, signal?: AbortSignal): Promise<NominatimItem[]> {
  const url = new URL('https://nominatim.openstreetmap.org/search')
  url.searchParams.set('format', 'jsonv2')
  url.searchParams.set('q', q)
  url.searchParams.set('accept-language', 'ru')
  url.searchParams.set('limit', '5')
  const res = await fetch(url.toString(), {
    headers: { 'User-Agent': 'craftshop-demo' },
    signal,
  })
  if (!res.ok) return []
  const data = (await res.json()) as NominatimItem[]
  return Array.isArray(data) ? data : []
}
