
const cache = {};

function getCache (r) {
	if (!r?.app?.locals) {
		return cache;
	}

	if (!r.app.locals.etags) {
		r.app.locals.etags = {};
	}

	return r.app.locals.etags;
}

function isCached (req) {
	const cache = getCache(req);

	if (req.url in cache) {
		const cached = cache[req.url];
		const etag = req.get("If-None-Match");
		if (etag && etag == cached.etag) {
			return cached;
		}
	}
	return; // undefined
}

function saveResponse (res) {
	if (res?.headersSent) {
		const etag = res.get("ETag");
		if (etag && res.locals.saveEtag !== false) {
			const cache = getCache(res);
			const req = res.req;
			console.log(`Saving ETag: ${req.method} ${req.url} → ${etag}`);
			const headers = structuredClone(res.getHeaders());
			delete headers["set-cookie"];
			cache[req.url] = {etag, headers};
		}
	}
};

module.exports = {
	getCache,
	isCached,
	saveResponse
};
