const api = {
	fetch: async function (url, __options) {
		const options = {
			method: "GET",
			...__options,
		};

		// FIXME: this will break with different server settings
		// TODO: we need the cookie names here to match any configured on the server
		const session_id = (document.cookie.match(
			/^(?:.*;)?\s*session_id\s*=\s*([^;]+)(?:.*)?$/,
		) || [, null])[1];

		// FIXME: this will break with different server settings
		// TODO: this wasn't really intended to be persisted in a cookie
		const session_secret = (document.cookie.match(
			/^(?:.*;)?\s*session_secret\s*=\s*([^;]+)(?:.*)?$/,
		) || [, null])[1];

		const headers = {
			Accept: "application/json",
			"x-session_id": session_id ?? "",
			"x-totp": session_secret ? await otp_totp(session_secret) : "",
			...(options.headers ?? {}),
		};

		const fetch_options = {
			method: options.method,
			headers,
			signal: options.signal,
		};

		if (options.json) {
			headers["Content-Type"] = "application/json";
			fetch_options.body = JSON.stringify(options.json);
		} else if (options.body) {
			fetch_options.body = options.body;
		}

		const response = await fetch(url, fetch_options);

		return response;
	},
};
