import { getConfig } from './config';
import axios, { AxiosResponse } from 'axios';
import { ReverseGeocodeResult, ReverseGeocodeOptions } from './types'; // Adjust the path as needed

export async function reverseGeocode(
  options: ReverseGeocodeOptions
): Promise<{ place: ReverseGeocodeResult; status: number }> {
  const apiKey = getConfig().apiKey;
  const version = getConfig().version;
  let apiUrl = '';
  if (version === 'v2') {
    apiUrl = `https://barikoi.xyz/v2/api/search/reverse/geocode`;
  } else {
    apiUrl = `https://barikoi.xyz/v1/api/search/reverse/${apiKey}/geocode`;
  }

  const params =
    version === 'v1' ? { ...options } : { api_key: apiKey, ...options };

  try {
    const response: AxiosResponse<{
      place: ReverseGeocodeResult;
      status: number;
    }> = await axios.get(apiUrl, {
      params,
    });

    return response.data; // Return the full response.data
  } catch (error) {
    console.error('Reverse Geocode request failed:', error.message);
    throw error;
  }
}
