const config = require("./config-handler");
const fs = require("fs");

function log(date, req, ip, res) {
	const requestBody = !req.byteBody.toString("utf-8")
		? ""
		: `
~~~~~~~~~~~~~~
[REQUEST BODY]
~~~~~~~~~~~~~~
${req.byteBody.toString("utf-8")}`;
	let action = `HTTP ${req.httpVersion} ${req.method} ${req.originalUrl}
~~~~~~~~~
[HEADERS]
~~~~~~~~~
${Object.entries(req.headers)
	.map(([header, value]) => header + ": " + value)
	.join("\n")}${requestBody}`;
	let response = !res.isError
		? ""
		: `\n----------------\nError raised:\n----------------\n${JSON.stringify(
				res.responseData,
		  )}`;
	//console.log(`================================\nREPORT\n================================\n\nIP: ${ip}\n----------------\nACTION:\n----------------\n${action}${response}`);
	let loggerFolder = config().logger_folder;
	loggerFolder = !["/", "\\"].includes(loggerFolder.at(-1))
		? loggerFolder + "/"
		: loggerFolder;

	fs.writeFileSync(
		`${loggerFolder}${date.getTime()}.log`,
		`================================\nREPORT\n================================\n\nIP: ${ip}\n----------------\nACTION:\n----------------\n${action}${response}`,
	);
}

module.exports = async (req, res, next) => {
	// console.log('ip', req.ip);
	log(new Date(), req, req.ip, res);
	next();
};