const CITY_PAIR_DISTANCE_KM = {
  'batumi::kutaisi': 150,
  'batumi::tbilisi': 370,
  'kutaisi::tbilisi': 230,
}

const FUEL_PRICE_USD_PER_LITER = 1.35

function normalizeKey(value) {
  return String(value || '').trim().toLowerCase().replace(/\s+/g, '-')
}

function normalizeCity(value) {
  return normalizeKey(value).replace(/-city$/, '')
}

function pairKey(left, right) {
  return [normalizeCity(left), normalizeCity(right)].sort().join('::')
}

function resolveVehicleConsumption(car) {
  const value = Number(car?.fuelConsumptionPer100Km ?? car?.specs?.fuelConsumptionPer100Km ?? car?.filterMeta?.specs?.fuelConsumptionPer100Km ?? 0)

  return Number.isFinite(value) && value > 0 ? value : null
}

export function resolveTripEconomy({ car, pickupLocation, dropoffLocation }) {
  const pickupCity = pickupLocation?.city || pickupLocation?.cityName || pickupLocation?.name
  const dropoffCity = dropoffLocation?.city || dropoffLocation?.cityName || dropoffLocation?.name
  const distanceKm = CITY_PAIR_DISTANCE_KM[pairKey(pickupCity, dropoffCity)] || 0
  const consumptionPer100Km = resolveVehicleConsumption(car)

  if (distanceKm <= 100 || !consumptionPer100Km) {
    return null
  }

  const fuelAmount = (distanceKm * consumptionPer100Km) / 100
  const estimatedCostUsd = Math.round(fuelAmount * FUEL_PRICE_USD_PER_LITER)

  return {
    distanceKm,
    routeLabel: `${pickupCity} → ${dropoffCity}`,
    consumptionLabel: `${consumptionPer100Km} L`,
    estimatedCostLabel: `~$${estimatedCostUsd}`,
  }
}
