import { haversineDistanceKm } from './distance';

export function inferLocationLabel(location, stores = [], options = {}) {
  if (
    !location ||
    typeof location !== 'object' ||
    !Number.isFinite(location.lat) ||
    !Number.isFinite(location.lon) ||
    !Array.isArray(stores) ||
    stores.length === 0
  ) {
    return null;
  }

  let closest = null;
  for (const store of stores) {
    const storeLat = Number(store?.location?.lat);
    const storeLon = Number(store?.location?.lon);
    if (!Number.isFinite(storeLat) || !Number.isFinite(storeLon)) {
      continue;
    }
    const distance = haversineDistanceKm(location.lat, location.lon, storeLat, storeLon);
    if (distance === null) {
      continue;
    }
    if (closest && distance >= closest.distance) {
      continue;
    }
    const labelParts = [];
    if (store.city) {
      labelParts.push(store.city);
    }
    if (store.region?.name) {
      const cityNormalized = store.city?.toLowerCase();
      const regionNormalized = store.region.name.toLowerCase();
      if (!cityNormalized || cityNormalized !== regionNormalized) {
        labelParts.push(store.region.name);
      }
    }
    if (labelParts.length === 0 && store.name) {
      labelParts.push(store.name);
    }
    const label = labelParts.length > 0 ? labelParts.join(' • ') : store.name || `Store ${store.id ?? ''}`.trim();
    closest = {
      label,
      distance
    };
  }

  if (!closest) {
    return null;
  }

  const result = {
    label: closest.label,
    distanceKm: closest.distance
  };
  if (Number.isFinite(options.maxDistanceKm)) {
    result.withinRange = closest.distance <= options.maxDistanceKm;
  }
  return result;
}
