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

const unknownError = (err) => {
	const stackId = new Date().getTime();
	let errorLoggingFolder = config().error_logs_folder;
	errorLoggingFolder = !["/", "\\"].includes(errorLoggingFolder.at(-1))
		? errorLoggingFolder + "/"
		: errorLoggingFolder;
	fs.writeFileSync(
		`${errorLoggingFolder}error_${stackId}.log`,
		`ERROR:
Date: ${new Date()}
Name: ${err.name}
Message: ${err.message}
Stack:
${err.stack}`,
	);

	return {
		error: "UNKNOWN_ERROR",
		details: {
			trace_id: stackId,
		},
	};
};

const unknownResponseFormat = "UNKNOWN_RESPONSE_FORMAT";

async function handlingError(funct, success, error) {
	try {
		success(await funct());
	} catch (e) {
		// console.log('error', e);
		error(
			e.name === "ApiError"
				? {
						error: e.message,
						details: e.details,
				  }
				: unknownError(e),
		);
	}
}

module.exports = async (method, req, res) => {
	if (req.query.response_format === "json") {
		handlingError(
			async () => ({ response: await method(req, res) }),
			async (data) => {
				res.sendModed(data);
			},
			async (errBody) => {
				res.errorModeOn();
				res.status(400).sendModed(errBody);
			},
		);
	} else {
		res.status(400).sendModed(unknownResponseFormat);
	}
};