import type {Coordinate, PlaceRef} from '@crumbs/core/schemas'

import {unwrap} from '@/lib/errors'
import {rpc} from '@/lib/rpc'

export const reverseGeocode = async (
  coord: Coordinate,
): Promise<PlaceRef | null> => {
  const {place} = await unwrap(
    rpc.places.reverse.$get({
      query: {
        lat: String(coord.latitude),
        lng: String(coord.longitude),
      },
    }),
  )
  return place
}

const EARTH_RADIUS_M = 6_371_000
const toRad = (deg: number) => (deg * Math.PI) / 180

export const metersBetween = (
  a: Coordinate,
  b: Coordinate,
): number => {
  const dLat = toRad(b.latitude - a.latitude)
  const dLon = toRad(b.longitude - a.longitude)
  const lat1 = toRad(a.latitude)
  const lat2 = toRad(b.latitude)
  const h =
    Math.sin(dLat / 2) ** 2 +
    Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) ** 2
  return 2 * EARTH_RADIUS_M * Math.asin(Math.sqrt(h))
}
