/**
 * Coordinate validation utilities for user-facing input.
 *
 * Potential improvement: a compact land/ocean grid (~8 KB as a bitset at 1°
 * resolution) could flag coordinates that land in the ocean, which is a
 * strong signal that the user swapped lat and lng. False positives are
 * possible (islands, coastal bookmarks), so it should be a soft warning,
 * not a hard error.
 */

export type CoordsValidation =
  | { ok: true }
  | { ok: false; error: string; suggestion?: { lat: number; lng: number } }

/**
 * Validate a lat/lng pair from user input.
 *
 * Checks that both values are numbers within legal ranges, and detects the
 * common mistake of entering coordinates in reverse order.
 */
export function validateCoords(lat: unknown, lng: unknown): CoordsValidation {
  const latN = Number(lat)
  const lngN = Number(lng)

  if (!Number.isFinite(latN) || !Number.isFinite(lngN)) {
    return { ok: false, error: 'Coordinates must be numbers.' }
  }

  const latOk = latN >= -90 && latN <= 90
  const lngOk = lngN >= -180 && lngN <= 180

  if (latOk && lngOk) return { ok: true }

  // If values would be valid when swapped, that's the likely mistake.
  const swappedLatOk = lngN >= -90 && lngN <= 90
  const swappedLngOk = latN >= -180 && latN <= 180
  if (swappedLatOk && swappedLngOk) {
    return {
      ok: false,
      error: 'Coordinates appear to be reversed.',
      suggestion: { lat: lngN, lng: latN },
    }
  }

  const parts: string[] = []
  if (!latOk) parts.push('latitude must be between -90 and 90')
  if (!lngOk) parts.push('longitude must be between -180 and 180')
  return { ok: false, error: `${parts[0]}.` }
}
