import type { Logger } from 'pino';
import { logger as defaultLogger } from './logger.server';

export class NominatimGeocodingService {
  /**
   * Geocodes an address using the public Nominatim API.
   * @param address The address string to geocode.
   * @param logger A logger instance.
   * @returns A promise that resolves to the coordinates or null if not found.
   */
  async geocode(address: string, logger: Logger = defaultLogger): Promise<{ lat: number; lng: number } | null> {
    const url = `https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(address)}&format=json&limit=1`;

    try {
      const response = await fetch(url, { headers: { 'User-Agent': 'FlyerCrawler/1.0' } });
      if (!response.ok) throw new Error(`Nominatim API returned status ${response.status}`);

      const data = await response.json();
      if (data && data.length > 0) {
        const { lat, lon } = data[0];
        logger.info({ address, result: { lat, lon } }, `[NominatimService] Successfully geocoded address`);
        return { lat: parseFloat(lat), lng: parseFloat(lon) };
      }
      logger.warn({ address }, '[NominatimService] Geocoding failed or returned no results.');
      return null;
    } catch (error) {
      logger.error({ err: error, address }, '[NominatimService] An error occurred while calling the Nominatim API.');
      return null;
    }
  }
}

export const nominatimGeocodingService = new NominatimGeocodingService();