/**
 * @ai-summary Helpers to build navigation URLs for stations
 */

// StationLike requires name, address, latitude, longitude for navigation
// placeId is optional (CommunityStation doesn't have it)
export interface StationLike {
  name: string;
  address: string;
  latitude: number;
  longitude: number;
  placeId?: string;
}

const hasValidCoordinates = (station: StationLike): boolean => {
  const { latitude, longitude } = station;
  if (typeof latitude !== 'number' || typeof longitude !== 'number') {
    return false;
  }

  if (Number.isNaN(latitude) || Number.isNaN(longitude)) {
    return false;
  }

  if (latitude === 0 && longitude === 0) {
    return false;
  }

  return true;
};

const getQuery = (station: StationLike): string => {
  return encodeURIComponent(station.address || station.name);
};

export interface NavigationLinks {
  google: string;
  apple: string;
  waze: string;
}

/**
 * Build navigation URLs for Google Maps, Apple Maps, and Waze.
 * Uses coordinates when available; falls back to address/name query.
 */
export const buildNavigationLinks = (station: StationLike): NavigationLinks => {
  if (hasValidCoordinates(station)) {
    const { latitude, longitude, placeId } = station;
    const latLng = `${latitude},${longitude}`;

    return {
      google: `https://www.google.com/maps/dir/?api=1&destination=${latLng}${
        placeId ? `&destination_place_id=${placeId}` : ''
      }`,
      apple: `https://maps.apple.com/?daddr=${latLng}`,
      waze: `https://waze.com/ul?ll=${latLng}&navigate=yes`
    };
  }

  const query = getQuery(station);

  return {
    google: `https://www.google.com/maps/search/?api=1&query=${query}`,
    apple: `https://maps.apple.com/?q=${query}`,
    waze: `https://waze.com/ul?q=${query}&navigate=yes`
  };
};
