import { toNonEmptyString } from '@/utils/stringNormalization';

export type ParsedMapCoordinates = {
  lat: number;
  lng: number;
};

const isInRange = (value: number, min: number, max: number) =>
  Number.isFinite(value) && value >= min && value <= max;

export const parseMapCoordinates = (
  rawCoordinates: string | null | undefined
): ParsedMapCoordinates | null => {
  const normalized = toNonEmptyString(rawCoordinates)?.replaceAll(' ', '');
  if (!normalized) return null;

  const parts = normalized.split(',');
  if (parts.length !== 2) return null;

  const latitude = Number.parseFloat(parts[0]);
  const longitude = Number.parseFloat(parts[1]);

  if (!isInRange(latitude, -90, 90) || !isInRange(longitude, -180, 180)) {
    return null;
  }

  return { lat: latitude, lng: longitude };
};

export const hasMapCoordinates = (rawCoordinates: string | null | undefined) =>
  Boolean(parseMapCoordinates(rawCoordinates));
