const YAML = require('yaml');
const { stringify } = require('csv-stringify/sync');
const { project } = require('../../../../lib/db');
const { flatEntries } = require('../../../../lib/utils/flatEntries');


function json (req, res, next) {
	if (res.locals.payload) {
		res.status(200).send(res.locals.payload);
	} else {
		res.status(404).send({message: "Not found"});
	}
}

function yaml (req, res, next) {
	if (res.locals.payload) {
		res.status(200).send(YAML.stringify(res.locals.payload));
	} else {
		res.status(404).send({message: "Not found"});
	}
}

function csv (req, res, next) {

	if (res.locals.payload) {
		const fields = [ "key", "value" ];
		const delimiter = req.query.delimiter ?? ",";
		const text = stringify([fields, ...flatEntries(res.locals.payload)], {delimiter});

		res.status(200).send(text);
	} else {
		res.status(404).send({message: "Not found"});
	}
}

module.exports = async function (req, res, next) {
	try {
		const handlers = {
			"application/json": json,
			"application/yaml": yaml,
			"text/csv": csv
		};

		const mimetype = (handlers[req.query.mime] && req.query.mime) || req.accepts(Object.keys(handlers));

		if (mimetype) {
			res.locals.payload = await project.configuration.get(req.params.project);

			res.set("Content-Type", mimetype);
			await handlers[mimetype](req, res, next);
		} else {
			res.status(406).send();
		}
		next();
	} catch (err) {
		console.error(err);
		next(err);
	}
}
