const { ALERT, ERROR, WARNING, NOTICE, INFO, DEBUG } = require('DOUGAL_ROOT/debug')(__filename);

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 req = res.req;
			if (res.get("set-cookie")) {
				// Do not save any responses containing cookies
				DEBUG(`Not caching due to cookies ${etag}: ${req.method} ${req.url}`);
				return;
			}
			const cache = getCache(res);
			DEBUG(`Caching ETag ${etag}: ${req.method} ${req.url}`);
			const headers = structuredClone(res.getHeaders());
			cache[req.url] = {etag, headers};
		}
	}
};

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