/**
 * Nominatim API client for geocoding
 * https://nominatim.openstreetmap.org/
 *
 * Usage policy: https://operations.osmfoundation.org/policies/nominatim/
 * Rate limit: 1 request per second
 */

import { NOMINATIM_API } from '../constants.js';

/**
 * @typedef {Object} GeocodingResult
 * @property {number} id - Place ID
 * @property {string} displayName - Full display name of the location
 * @property {number} lat - Latitude
 * @property {number} lon - Longitude
 * @property {string} type - Location type (city, street, etc.)
 * @property {number} importance - Importance score
 * @property {Array<string>} boundingBox - Bounding box coordinates
 */

/**
 * Search for an address using Nominatim API
 *
 * @param {string} query - Address to search for
 * @returns {Promise<Array<GeocodingResult>>} Array of geocoding results
 * @throws {Error} When API request fails
 *
 * @example
 * const results = await geocode('Paris, France');
 * console.log(results[0].displayName); // "Paris, Île-de-France, France"
 */
export async function geocode(query) {
  if (!query || query.trim().length < NOMINATIM_API.MIN_QUERY_LENGTH) {
    return [];
  }

  try {
    const params = new URLSearchParams({
      q: query.trim(),
      format: 'json',
      addressdetails: '1',
      limit: String(NOMINATIM_API.MAX_RESULTS),
      'accept-language': NOMINATIM_API.DEFAULT_LANGUAGE,
    });

    const response = await fetch(
      `${NOMINATIM_API.BASE_URL}?${params.toString()}`,
      {
        headers: {
          'User-Agent': NOMINATIM_API.USER_AGENT,
        },
      }
    );

    if (!response.ok) {
      throw new Error(`Nominatim API error: ${response.status}`);
    }

    const data = await response.json();

    // Transform results to a consistent format
    return data.map((result) => ({
      id: result.place_id,
      displayName: result.display_name,
      lat: parseFloat(result.lat),
      lon: parseFloat(result.lon),
      type: result.type,
      importance: result.importance,
      boundingBox: result.boundingbox,
    }));
  } catch (error) {
    console.error('Geocoding error:', error);
    throw error;
  }
}
