/**
 * Shared helpers: OSM tags → single-line address, element → pharmacy row.
 */

import { parseOsmOpeningHours } from './opening-hours-osm.js';

export function buildAddressFromOsmTags(tags) {
  if (!tags || typeof tags !== 'object') return '';
  if (tags['addr:full'] && String(tags['addr:full']).trim()) {
    return String(tags['addr:full']).trim();
  }
  const street = [tags['addr:street'], tags['addr:housenumber']].filter(Boolean).join(' ').trim();
  const cityLine = [tags['addr:postcode'], tags['addr:city'] || tags['addr:place'] || tags['addr:suburb']]
    .filter(Boolean)
    .join(' ')
    .trim();
  const parts = [street, cityLine].filter(Boolean);
  if (parts.length) return parts.join(', ');
  if (tags['addr:province'] && tags['addr:city']) {
    return `${tags['addr:city']}, ${tags['addr:province']}`.trim();
  }
  return '';
}

/**
 * @param {object} el - Overpass element (node | way | relation with optional center)
 */
export function osmElementToPharmacy(el) {
  const tags = el.tags || {};
  let lat;
  let lon;
  if (el.type === 'node' && el.lat != null && el.lon != null) {
    lat = Number(el.lat);
    lon = Number(el.lon);
  } else if (el.center && el.center.lat != null && el.center.lon != null) {
    lat = Number(el.center.lat);
    lon = Number(el.center.lon);
  }

  const name = tags.name || tags.brand || tags.operator || null;
  let address = buildAddressFromOsmTags(tags);
  if (!address && tags['addr:country']) {
    address = tags['addr:city'] || tags['addr:place'] || '';
  }
  if (!address && name) {
    address = `OpenStreetMap (no address tags; id ${el.type}/${el.id})`;
  }

  const phone =
    tags.phone || tags['contact:phone'] || tags['contact:mobile'] || tags['contact:whatsapp'] || null;

  const opening_hours = parseOsmOpeningHours(tags.opening_hours);

  return {
    name,
    address: address || null,
    phone: phone ? String(phone).trim() : null,
    latitude: Number.isFinite(lat) ? lat : null,
    longitude: Number.isFinite(lon) ? lon : null,
    opening_hours: opening_hours || null,
  };
}
