const cache = new Map();
const key = 'hulk_affef_telephone_geoIpLookup';
const defaultCode = 'us';

async function ipapi() {
	const response = await fetch('https://ipapi.co/json');
	if (!response.ok) {
		throw response;
	}
	const data = await response.json();
	return data?.country_code || '';
}

async function geojs() {
	const response = await fetch('https://get.geojs.io/v1/ip/country.json');
	if (!response.ok) {
		throw response;
	}
	const data = await response.json();
	return data?.country || '';
}

async function lookup(): Promise<string> {
	return ipapi()
		.then(value => value)
		.catch(() => geojs())
		.then(value => value)
		.catch(() => defaultCode)
}

function geoIpLookup() {
	if (!cache.has(key)) {
		cache.set(key, lookup());
	}
	return cache.get(key);
}

export default geoIpLookup
