// services/nominatimService.ts
import { socket } from 'boot/socketio';
import type { NominatimRequest, GeoCacheResponse } from 'components/models';



let lastRequestTime = 0;

function revGeoCode(nomRequest: NominatimRequest): Promise<GeoCacheResponse> {
  return new Promise((resolve) => {
    socket.emit(
      'reverse_geocode',
      { latitude: nomRequest.latitude, longitude: nomRequest.longitude },
      (response) => {
        resolve(response);
      },
    );
  });
}

export const reverseGeocodeRateLimited = async (lat: number, lon: number): Promise<GeoCacheResponse> => {
  const now = Date.now();
  const timeSinceLast = now - lastRequestTime;

  // Wait if less than 1000ms has passed
  if (timeSinceLast < 1000) {
    await new Promise((resolve) => setTimeout(resolve, 1000 - timeSinceLast));
  }
  const response: GeoCacheResponse = await revGeoCode({
    latitude: lat,
    longitude: lon,
  } as NominatimRequest);

  lastRequestTime = Date.now();
  return response;
};
