export const IP_LOCATION_CACHE_KEY = 'cliq-sl-ip-location-v1';

export const normaliseIpLocation = ( value ) => {
	const rawLat = value?.latitude ?? value?.lat;
	const rawLng = value?.longitude ?? value?.lng;
	if ( rawLat === null || rawLat === undefined || rawLat === '' || rawLng === null || rawLng === undefined || rawLng === '' ) return null;
	const lat = Number( rawLat );
	const lng = Number( rawLng );
	if ( ! Number.isFinite( lat ) || ! Number.isFinite( lng ) || lat < -90 || lat > 90 || lng < -180 || lng > 180 ) {
		return null;
	}
	const accuracy = Number( value?.accuracy );
	return {
		lat,
		lng,
		source: 'ip',
		...( Number.isFinite( accuracy ) && accuracy >= 0 ? { accuracy } : {} ),
	};
};

export const readCachedIpLocation = ( storage ) => {
	try {
		return normaliseIpLocation( JSON.parse( storage?.getItem( IP_LOCATION_CACHE_KEY ) || 'null' ) );
	} catch ( error ) {
		return null;
	}
};

export const cacheIpLocation = ( storage, location ) => {
	try {
		storage?.setItem( IP_LOCATION_CACHE_KEY, JSON.stringify( location ) );
	} catch ( error ) {} // Storage may be disabled; the live result is still usable.
};
