/**
 * FarmaClic external pharmacy sources (OpenStreetMap, Google Places, open-data URLs).
 * Used by the backend admin import; OSM does not require n8n.
 */

export { buildAddressFromOsmTags, osmElementToPharmacy } from './normalize.js';
export { fetchPharmaciesFromOsm } from './osm-overpass.js';
export { fetchPharmaciesFromOpenDataUrl } from './open-data.js';

import { fetchPharmaciesFromOsm } from './osm-overpass.js';
import { fetchPharmaciesFromOpenDataUrl } from './open-data.js';

/**
 * @param {{
 *   source: 'osm' | 'openData',
 *   lat?: number|string,
 *   lon?: number|string,
 *   lng?: number|string,
 *   radio?: number|string,
 *   openDataUrl?: string,
 * }} opts
 */
export async function fetchPharmaciesExternal(opts) {
  const source = opts?.source;
  if (source === 'openData') {
    return fetchPharmaciesFromOpenDataUrl(opts.openDataUrl);
  }

  const lat = parseFloat(opts.lat);
  const lon = parseFloat(opts.lon ?? opts.lng);
  const radio = parseFloat(opts.radio) || 1500;

  if (!Number.isFinite(lat) || !Number.isFinite(lon)) {
    throw new Error('lat and lon are required for osm sources');
  }

  if (source === 'osm') {
    return fetchPharmaciesFromOsm({
      lat,
      lon,
      radiusMeters: radio,
    });
  }

  throw new Error('source must be "osm", or "openData"');
}
