// Dependencies and Modules
const User = require("../models/User");
const bcrypt = require("bcrypt");

// Auth
const auth = require("../auth");

module.exports.registerUser = (reqBody) => {
	let newUser = new User({
		firstName: reqBody.firstName,
		lastName: reqBody.lastName,
		email: reqBody.email,
		mobileNo: reqBody.mobileNo,
		password: bcrypt.hashSync(reqBody.password, 10)
		
	});

	return newUser.save().then((user, error) => {
		if(error){
			return false;
		} else {
			return true;
		}
	});
}

module.exports.loginUser = (req, res) => {
	return User.findOne({email: req.body.email}).then(result => {
		if(result == null){
			return false;
		} else {
			const isPasswordCorrect = bcrypt.compareSync(req.body.password, result.password);
			if(isPasswordCorrect) {
				res.send({
					access: auth.createAccessToken(result)
				});
			} else {
				return res.send(false);
			}
		}
	});
}

module.exports.retrieveDetails = async (req, res) => {
    try {
        const user = await User.findById(req.user.id);
        if (!user) {
            return res.send(false);
        }
        user.password = ''; // Set password to an empty string
        return res.send(user);
    } catch (error) {
        console.error(error);
        return res.status(500).send('Internal Server Error');
    }
}


