import type { LatLngPosition } from '../types';

// AZ-501 — Google Geocode lookup, mirrors the WeatherService pattern from
// AZ-499: build-time env var, fail-soft when unset, fail-soft on network errors.
// Extracted from LeftBoard.tsx so the env-resolution and fail-soft contract
// can be unit-tested in isolation.

const ENDPOINT = 'https://maps.googleapis.com/maps/api/geocode/json';

export const geocodeAddress = async (
  address: string,
): Promise<LatLngPosition | null> => {
  const apiKey = import.meta.env.VITE_GOOGLE_GEOCODE_KEY;
  if (!apiKey) {
    // Surface the misconfiguration — geocode is user-triggered (per "Enter"
    // keypress) so a single warn per call is informative, not spammy.
    console.warn(
      '[geocodeAddress] VITE_GOOGLE_GEOCODE_KEY is not set; skipping lookup',
    );
    return null;
  }

  const url = `${ENDPOINT}?address=${encodeURIComponent(address)}&key=${apiKey}`;

  try {
    const response = await fetch(url);
    const data = await response.json();
    if (data.status === 'OK' && data.results.length > 0) {
      const location = data.results[0].geometry.location;
      return { lat: location.lat, lng: location.lng };
    }
  } catch {
    return null;
  }
  return null;
};
