// middlewares/auth.js

const jwt = require("jsonwebtoken")
require("dotenv").config()

// Middleware for verifying and authenticating JWT token
exports.authenticateToken = (req, res, next) => {
	// Extract the token from the Authorization header
	const token = req.header("Authorization")?.replace("Bearer ", "")

	if (!token) {
		return res
			.status(401)
			.json({ message: "Unauthorized. Token not provided." })
	}

	console.log("Token:", token) // Log the token to the console

	try {
		const decoded = jwt.verify(token, process.env.SECRET_SAUCE)
		req.user = decoded // Attach the decoded information to the request for future use

		// dEBUGGING PURPOSES
		console.log("userId:", decoded.userId)
		console.log("isAdmin:", decoded.isAdmin)

		next()
	} catch (error) {
		console.error("Token Verification Error:", error)
		return res
			.status(401)
			.json({ message: "Unauthorized. Invalid or expired token." })
	}
}

// Function to generate a JWT token
exports.generateToken = (userId, email, isAdmin) => {
	return jwt.sign({ userId, email, isAdmin }, process.env.SECRET_SAUCE, {
		expiresIn: "1h",
	})
}

// Middleware to verify admin status
exports.verifyAdmin = (req, res, next) => {
	if (req.user && req.user.isAdmin) {
		next()
	} else {
		return res
			.status(403)
			.json({ message: "Action Forbidden. User is not an admin." })
	}
}

exports.verifyUser = (req, res, next) => {
	const authenticatedUserId = req.user.userId;
	const requestedUserId = req.body.userId;
  
	if (authenticatedUserId && authenticatedUserId === requestedUserId) {
	  // User is authenticated, and the requested userId matches the authenticated userId
	  next();
	} else {
	  return res.status(403).json({
		message: "Permission denied.",
	  });
	}
  };
  