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

function isIdempotentMethod (method) {
	const nonIdempotentMethods = [
		"POST", "PUT", "PATH", "DELETE"
	];

	return !nonIdempotentMethods.includes(method.toUpperCase());
};

function setHeaders(res, headers) {
	for (let [key, value] of Object.entries(headers)) {
		res.set(key, value);
	}
	return res;
}


function ifNoneMatch (req, res, next) {

	const cached = isCached(req);
	if (cached) {
		DEBUG("ETag match. Returning cached response (ETag: %s, If-None-Match: %s) for %s %s",
			  cached.etag, req.get("If-None-Match"), req.method, req.url);
		if (req.method == "GET" || req.method == "HEAD") {
			setHeaders(res, cached.headers);
			res.status(304).end();
			// No next()
		} else if (!isIdempotentMethod(req.method)) {
			res.status(412).send();
		}
	} else {
		// Either we didn't have this URL in the cache, or there was
		// no If-None-Match header, or it didn't match the cached ETag.
		// We let the request proceed normally.
		next();
	}
}

module.exports = ifNoneMatch;
