const db = require("../models");
const ROLES = db.ROLES;
const User = db.user;

checkDuplicateUsernameOrEmail = async (req, res, next) => {
	try {
		const userByUsername = await User.findOne({
			username: req.body.username,
		}).exec();
		if (userByUsername) {
			return res.send({
				status: false,
				message: "Uživatelské jméno je již zabrané!",
			});
		}

		const userByEmail = await User.findOne({ email: req.body.email }).exec();
		if (userByEmail) {
			return res.send({ status: false, message: "E-mail je již zabrán!" });
		}

		next();
	} catch (err) {
		res.send({ message: err.message });
	}
};

checkRolesExisted = (req, res, next) => {
	if (req.body.roles) {
		for (let i = 0; i < req.body.roles.length; i++) {
			if (!ROLES.includes(req.body.roles[i])) {
				return res.send({
					message: `Role ${req.body.roles[i]} neexistuje!`,
				});
			}
		}
	}

	next();
};

const verifyRegister = {
	checkDuplicateUsernameOrEmail,
	checkRolesExisted,
};

module.exports = verifyRegister;
