const User = require("../models/User.js");
const Product = require("../models/Product.js");
const Order = require("../models/Order.js");
const bcrypt = require("bcryptjs");
const auth = require("../auth.js");
const {verify, verifyAdmin} = auth;

// Controllers

// Check email controller
module.exports.checkEmailExists = (request, response, next) => {
	let reqBody = request.body;

	User.find({email : reqBody.email})
	.then(result => {
		if(result.length > 0){
			return response.send(false);
		}else{
			next();
		}
	})
	.catch(error => response.send(false));
}

// Register user controller
module.exports.registerUser = (request, response) => {
	const reqBody = request.body;

	const newUser = new User({
		email: reqBody.email,
		password: bcrypt.hashSync(reqBody.password, 10)
	})

	newUser.save().then(save => {
		return response.send(true)
	}).catch(error => {
		return response.send(false);
	})
}

// Login controller
module.exports.loginUser = (request, response) => {
	const reqBody = request.body;

	User.findOne({email : reqBody.email}).then(result => {
		if(result === null) {
			return response.send(false);
		}else{

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

			if(isPasswordCorrect){

				const token = auth.createAccessToken(result);

				return response.send({accessToken: token});

			}else{
				return response.send(false);
			}
		}
	})
}


// get current user details controller.
exports.getCurrentUserDetails = async (req, res) => {
  try {
    const user = await User.findById(req.user.id, 'email');

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

    res.json(user);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error fetching user details' });
  }
};


// set user to admin controller.
exports.setUserAsAdmin = async (req, res) => {
  try {
    const { userId } = req.body;

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

    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }else if(user.isAdmin === true) {
    	return res.status(404).json({ message: 'User already an Admin' });
    }

    // Set the user's isAdmin property to true
    user.isAdmin = true;

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

    res.json({ message: 'User set as admin successfully' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error setting user as admin' });
  }
};


// get current user orders controller.
exports.getCurrentUserOrders = async (req, res) => {
  try {
    const user = await User.findById(req.user.id, 'orders');

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

    res.json(user);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error fetching orders' });
  }
};


// retrieve all orders controller
module.exports.getAllOrders = async (req, res) => {
  try {
    // Fetch all products from the database
    const orders = await Order.find();

    res.json(orders);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Error retrieving Orders' });
  }
};