/**
 * Forward geocoding via OpenStreetMap Nominatim — same free, no-API-key OSM
 * ecosystem the map tiles come from. Used by the provider-registration map
 * picker to turn a typed place / the entered address into map coordinates.
 *
 * NOT routed through our axios instance: this is an external public service, so
 * a plain `fetch` (no auth headers / base URL) is correct. Nominatim asks
 * callers to keep volume low (≤1 req/s) and to identify themselves — the browser
 * supplies a Referer automatically, and we only query on an explicit user action
 * (search submit / "use address" button), never per keystroke.
 */

const ENDPOINT = "https://nominatim.openstreetmap.org/search";

export interface GeocodeResult {
  lat: number;
  lng: number;
  /** Human-readable place name for the results list */
  label: string;
}

export async function geocodePlace(
  query: string,
  options: { language?: string; signal?: AbortSignal; limit?: number } = {},
): Promise<GeocodeResult[]> {
  const term = query.trim();
  if (!term) return [];

  const params = new URLSearchParams({
    q: term,
    format: "jsonv2",
    addressdetails: "0",
    limit: String(options.limit ?? 5),
    // Pilot operates in Saudi Arabia — bias results there.
    countrycodes: "sa",
  });

  const res = await fetch(`${ENDPOINT}?${params.toString()}`, {
    signal: options.signal,
    // Accept-Language is a CORS-safelisted header (no preflight) and localises
    // the returned place names to the user's chosen language.
    headers: { "Accept-Language": options.language ?? "en" },
  });
  if (!res.ok) throw new Error(`Geocoding failed: ${res.status}`);

  const data = (await res.json()) as Array<{
    lat: string;
    lon: string;
    display_name: string;
  }>;

  return data
    .map((d) => ({
      lat: Number(d.lat),
      lng: Number(d.lon),
      label: d.display_name,
    }))
    .filter((r) => Number.isFinite(r.lat) && Number.isFinite(r.lng));
}
