// services/nominatimService.ts
import { api } from 'boot/axios';
import type { NominatimResponse, NominatimRequest } from 'components/models';

let lastRequestTime = 0;

export const reverseGeocodeRateLimited = async (
  lat: number,
  lon: number,
): Promise<NominatimResponse> => {
  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 = await api.post<NominatimResponse>('/rev_geocode', {
    latitude: lat,
    longitude: lon,
  } as NominatimRequest);

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