/**
 * Converts PostgreSQL point format to JSON object format
 * PostgreSQL point can come as:
 * - String: "(lat,lng)"
 * - Object: {x: lat, y: lng}
 * - Already in JSON format: {lat, lng}
 */
export function postgresPointToJson(point: any): { lat: number; lng: number } | null {
  if (!point) return null;
  
  // If it's already in the correct JSON format
  if (typeof point === 'object' && 'lat' in point && 'lng' in point) {
    return point;
  }
  
  // If it's a string like "(lat,lng)"
  if (typeof point === 'string') {
    const match = point.match(/^\s*\(\s*(-?\d+\.?\d*)\s*,\s*(-?\d+\.?\d*)\s*\)\s*$/);
    if (match) {
      return {
        lat: parseFloat(match[1]),
        lng: parseFloat(match[2])
      };
    }
  }
  
  // If it's an object with x,y properties (PostgreSQL point object)
  if (typeof point === 'object' && 'x' in point && 'y' in point) {
    return {
      lat: parseFloat(point.x),
      lng: parseFloat(point.y)
    };
  }
  
  console.warn('Unexpected location format:', point);
  return null;
}

/**
 * Converts JSON object format to PostgreSQL point format
 * Returns a string in the format "(lat,lng)"
 */
export function jsonToPostgresPoint(location: { lat: number; lng: number } | null): string | null {
  if (!location) return null;
  return `(${location.lat},${location.lng})`;
}

/**
 * Type guard to check if a value is a valid location object
 */
export function isValidLocation(obj: any): obj is { lat: number; lng: number } {
  return obj && 
         typeof obj === 'object' && 
         typeof obj.lat === 'number' && 
         typeof obj.lng === 'number' &&
         !isNaN(obj.lat) && 
         !isNaN(obj.lng);
}