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

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

// Contoller function to check if email already exists
/*
	Business Logic:
		1. Use mongoose "find" method to find duplicate emails
		2. Use the "then" method to send the response back to the frontend application based on the result of the "find" method
*/  
module.exports.checkEmailExists = (reqBody) => {

	return User.find({ email: reqBody.email }).then(result => {

		// The "find" method returns a record if a match is found
		// It will be returned as an array
		// Return true if there exist an email in the DB
		if(result.length > 0){
			return true;

		// No duplicate email found, return false
		} else {
			return false;
		}
	});
}

// User registration controller
/*
	MINI ACTIVITY
	registerUser
	Steps:
		1. Create a new User object using the mongoose model and the information from the request body
			- firstName
			- lastName
			- email
			- mobileNo
			- password
		2. Make sure that the password is encrypted
		3. Save the new User to the database
*/
module.exports.registerUser = (reqBody) => {

	// Creates a variable "newUser" and instantiates a new "User" object using the mongoose model
	// Uses the information from the request body to provide all the necessary informate
	let newUser = new User({
		firstName: reqBody.firstName,
		lastName: reqBody.lastName,
		email: reqBody.email,
		mobileNo: reqBody.mobileNo,
		// 10 is the value provided as the number of "salt" rounds that the bcrypt algorithm will run in order to encrypt the password
		password: bcrypt.hashSync(reqBody.password, 10)
	});

	// Saves the created object to our database
	return newUser.save().then((user, error) => {

		// User registration fails
		if(error){
			return false

		// User registration succeed
		} else {
			return true
		}
	});
}


// User Authentication Controller
/*
	Steps: 
		1. Check the database if the user email exists
		2. Compare the password provided in the login form with the password stored in the database.
		3. Generate/return a JSON web token (access token) if the user is successfully logged in and return false if not
*/
module.exports.loginUser = (req, res) => {

	return User.findOne({email: req.body.email}).then(result => {

		// If User does not exist
		if(result == null){

			return false;

		// If user exists
		} else {

			const isPasswordCorrect = bcrypt.compareSync(req.body.password, result.password);

			if(isPasswordCorrect) {

				res.send({
					access: auth.createAccessToken(result)
				});
			} else {

				return res.send(false);
			}
		}
	});
}

// Retrieve User Details Controller
/*
	Steps:
		1. Find the document in the db using the user's ID
		2. Reassign the password of the returned document to an empty string
		3. Return the result back to the frontend
*/
// module.exports.getProfile = (req, res) => {

// 	return User.findById(req.user.id).then(result => {

// 		// Changes the value of the user's password to an empty string for security
// 		result.password = "";

// 		// Returns the user information with the password as an empty string
// 		return res.send(result);

// 		//if there are errors finding the document
// 	}).catch(error => res.send(error));
// }

// // Enroll User to a Course
// /*
// 	Steps:
// 		1. Find the document in the db using the user's ID
// 		2. Add the course ID to the user's enrollment array
// 		3. Update the document in the MongoDB database
// */
// module.exports.enroll = async (req, res) => {


// 	// The admin is not allowed to enroll to a course
// 	if(req.user.isAdmin){
// 		return res.send("Action forbidden")
// 	}

// 	// Store the value true to the isUserUpdated variable if the enrollment is successful
// 	let isUserUpdated = await User.findById(req.user.id).then(user => {

// 		// Add the courseId in an object and push that object into the user's enrollment array 
// 		let newEnrollment = {
// 			courseId: req.body.courseId,
// 			courseName: req.body.courseName,
// 			courseDescription: req.body.courseDescription,
// 			coursePrice: req.body.coursePrice
// 		}

// 		user.enrollments.push(newEnrollment);

// 		// Return true if the saving is successful or return the error message if there are errors
// 		return user.save().then(user => true).catch(error => error.message);

// 	});


// 	// Checks if isUserUpdated is not true
// 	if(isUserUpdated !== true){

// 		return res.send({
// 			message: isUserUpdated
// 		});
// 	}

// 	//  Find the course and update the enrollees array of that course with the user id
// 	let isCourseUpdated = await Course.findById(req.body.courseId).then(course => {

// 		let enrollee = {
// 			userId: req.user.id
// 		}

// 		course.enrollees.push(enrollee);

// 		return course.save().then(course => true).catch(error => error.message);

// 	});


// 	// Check if there was an error saving our course document
// 	if(isCourseUpdated !== true){
// 		return res.send({
// 			message: isCourseUpdated
// 		});
// 	}

// 	// Checks if isUserUpdated and isCourseUpdated is true, then the enrollment is successful
// 	if(isUserUpdated && isCourseUpdated){
// 		return res.send({
// 			message: "Enrolled Successfully."
// 		});
// 	}


// }


// // Function to reset the password
// module.exports.resetPassword = async (req, res) => {
//   try {
//     const { newPassword } = req.body;
//     const { id } = req.user; // Extracting user ID from the authorization header

//     // Hashing the new password
//     const hashedPassword = await bcrypt.hash(newPassword, 10);

//     // Updating the user's password in the database
//     await User.findByIdAndUpdate(id, { password: hashedPassword });

//     // Sending a success response
//     res.status(200).json({ message: 'Password reset successfully' });
//   } catch (error) {
//     console.error(error);
//     res.status(500).json({ message: 'Internal server error' });
//   }
// };


// // Controller function to update the user profile
// module.exports.updateProfile = async (req, res) => {
//   try {
//     // Get the user ID from the authenticated token
//     const userId = req.user.id;

//     // Retrieve the updated profile information from the request body
//     const { firstName, lastName, mobileNo } = req.body;

//     // Update the user's profile in the database
//     const updatedUser = await User.findByIdAndUpdate(
//       userId,
//       { firstName, lastName, mobileNo },
//       { new: true }
//     );

//     res.json(updatedUser);
//   } catch (error) {
//     console.error(error);
//     res.status(500).json({ message: 'Failed to update profile' });
//   }
// };


// module.exports.getEnrollments = (req, res) => {

// 	return User.findById(req.user.id).then(foundUser => {
// 		return res.send(foundUser.enrollments);
// 	})
	
// };

// module.exports.resetPassword = async (req, res) => {
//   try {
//     const password = req.body.password;
//     console.log(password);
//     let userId = req.user.id; // Extracting user ID from the authorization header
//     console.log(userId);
//     // Hashing the new password
//     let hashedPassword = bcrypt.hashSync(password, 10);
//     console.log(hashedPassword);
//     // Updating the user's password in the database
//     return User.findByIdAndUpdate(userId, { password: hashedPassword }).then(result => {
//     	return res.send(result);
//     })
//     // Sending a success response
// 	}
// 	catch(error) {
// 		 return res.send(error);
// 	}

// }

// module.exports.updateProfile = async (req, res) => {
//   try {
//     // Get the user ID from the authenticated token
//     let userId = req.user.id;

//     // Retrieve the updated profile information from the request body
//     let { firstName, lastName, mobileNumber, email } = req.body;

//     // Update the user's profile in the database
//     const updatedUser = await User.findByIdAndUpdate(
//       userId,
//       { firstName, lastName, email, mobileNumber },
//       { new: true }
//     );

//     res.json(updatedUser);
//   } catch (error) {
//     console.error(error);
//     res.status(500).json({ message: 'Failed to update profile' });
//   }
// }

// module.exports.updateEnrollmentStatus = async (req,res) => {
// 	try {
// 	  const { userId, courseId } = req.body;
// 	  const { updatedStatus } = req.body;

// 	  // Check if the user and course exist
// 	  const user = await User.findById(userId);
// 	  if (!user) {
// 	    return res.status(404).json({ message: 'User not found.' });
// 	  }

// 	  const courseIndex = user.enrollments.findIndex((enrollment) => enrollment.courseId === courseId);

// 	  if (courseIndex === -1) {
// 	    return res.status(404).json({ message: 'Course not found in user\'s enrollments.' });
// 	  }
// 	  // Update the enrollment status
// 	      user.enrollments[courseIndex].status = updatedStatus;

// 	      // Save the updated user object
// 	      await user.save();

// 	      res.status(200).json({ message: 'Enrollment status updated successfully.' });
// 	    } catch (err) {
// 	      console.error(err);
// 	      res.status(500).json({ message: 'Internal server error.' });
// 	    }
// }


// Controller function to update a user as an admin
// exports.updateUserAsAdmin = async (req, res) => {
//   try {
//     const { userId } = req.body;

//     // Find the user by userId
//     const user = await User.findById(userId);

//     if (!user) {
//       return res.status(404).json({ message: 'User not found' });
//     }

//     // Update the user as an admin
//     user.isAdmin = true;
//     await user.save();

//     res.status(200).json({ message: 'User updated as admin successfully' });
//   } catch (error) {
//     console.error(error);
//     res.status(500).json({ message: 'An error occurred while updating the user as admin' });
//   }
// };








