var userService = require("../userDBServices");
var User = require("../models/user");

var registerUserController = async (req, res) => {
	try {
		console.log(req.body);
		var status = await userService.createUserDBService(req.body);
		console.log(status);

		if (status) {
			res.send({ status: true, message: "Registrace proběhla úspěšně" });
		} else {
			res.send({ status: false, message: "Chyba při registraci" });
		}
	} catch (error) {
		console.log(error);
	}
};

var loginUserController = async (req, res) => {
	var result = null;
	try {
		result = await userService.loginUserDBService(req.body);
		if (result.status) {
			res.send({
				status: true,
				message: result.msg,
				token: result.token,
				username: result.user.username,
				userId: result.user.id,
			});
		} else {
			res.send({ status: false, message: result.msg });
		}
	} catch (error) {
		console.log(error);
		res.send({ status: false, message: error.msg });
	}
};

var fetchAllUsers = async (req, res) => {
	try {
		const users = await User.find();
		res.json(users);
	} catch (error) {
		res.send({ error: error.message });
	}
};

var fetchUser = async (req, res) => {
	const groupId = req.params.groupId;
	try {
		const usersInGroup = await User.find({ group: groupId });
		res.send(usersInGroup);
	} catch (error) {
		res.send({ error: error.message });
	}
};

var updateGroup = async (req, res) => {
	const userId = req.params.id;
	const newGroup = req.body.group;
	try {
		const updatedUser = await User.findByIdAndUpdate(
			userId,
			{ group: newGroup },
			{ new: true },
		);
		if (!updatedUser) {
			return res.send("Uživatel nenalezen");
		}
		res.json(updatedUser);
	} catch (error) {
		res.send({ "Error při aktualizaci uživatele": error });
	}
};

var getPreference = async (req, res) => {
	try {
		const user = await User.findById(req.params.userId).select(
			"preference_holiday preference_adjacent",
		);
		if (!user) return res.send({ message: "Uživatel nenalezen" });

		res.send({
			holiday: user.preference_holiday,
			adjacent: user.preference_adjacent,
		});
	} catch (error) {
		console.log(error);
		res.send({ message: "Server error" });
	}
};

var updatePreference = async (req, res) => {
	try {
		const { holiday, adjacent } = req.body;

		const user = await User.findByIdAndUpdate(
			req.params.userId,
			{
				preference_holiday: holiday,
				preference_adjacent: adjacent,
			},
			{ new: true },
		).select("preference_holiday preference_adjacent");
		if (!user) return res.send({ message: "Uživatel nenalezen" });

		res.send({ message: "Prefence byli úspěšně aktualizovány", user });
	} catch (error) {
		console.log(error);
		res.send({ message: "Server error" });
	}
};

module.exports = {
	registerUserController,
	loginUserController,
	fetchAllUsers,
	fetchUser,
	updateGroup,
	getPreference,
	updatePreference,
};
