// Send request to backend API
function request(method, path, data = null) {
	return new Promise((resolve, reject) => {
		const xhr = new XMLHttpRequest();

		xhr.onload = () => {
			if (xhr.status >= 200 && xhr.status < 300)
				resolve(xhr.responseText ? JSON.parse(xhr.responseText) : null);
			else
				reject(xhr.responseText || "HTTP " + xhr.status);
		}

		xhr.onerror = () => reject("Something went wrong");

		xhr.withCredentials = true;
		xhr.open(method, import.meta.env.VITE_API_URL + path);

		if (data) {
			xhr.setRequestHeader("Content-Type", "application/json");
			xhr.send(JSON.stringify(data));
		} else {
			xhr.send();
		}
	});
}

export {
	request,
};

