
const ServerUser = require('../../../lib/db/user/User');

module.exports = async function (req, res, next) {

	try {
		// const data = await user.create(req.body, req.user?.organisations);
		// res.status(203).send(data);
		const requestor = new ServerUser(req.user);
		if (requestor.name) {
			const target = await ServerUser.fromSQL(null, req.params.user_id);
			const changes = req.body;

			if (requestor.id == target.id || requestor.canEdit(target)) {

				if (requestor.id == target.id) {
					// User cannot self-deactivate
					target.active = requestor.active;
				}

				const edited = await requestor.edit(target).to(changes).save();

				if (edited instanceof ServerUser) {
					res.status(200).send(edited.toJSON());
				} else {
					console.log("Unexpected result", edited);
					throw({status: 500, message: "Unexpected response when editing user"});
				}
			} else {
				next({status: 403, message: "Access denied"});
			}
		}
		next();
	} catch (err) {
		next(err);
	}

};
