const asyncHandler = require("express-async-handler");
const jwt = require("jsonwebtoken");

const authenticateUser = asyncHandler ( async (req, res, next) => {
    var authcookie = req.cookies.authcookie;
    if(!authcookie) {
        res.redirect('/admin/login');
        return;
    }else{
        jwt.verify(authcookie, process.env.ACCESS_TOKEN_SECRET, (err, decode) => {
            if(!err) {
                req.user = decode.user;
                console.log(req.user);
            }else{
                console.log("there was some error "+ err);
                res.redirect('/admin/login');
            }
        });
    }
    next();
});

const authorize = (req, res, next) => {
    const userRole = req.user.role; // Assuming `req.user` is populated from authentication middleware
    const route = req.baseUrl + req.path; // Get the requested route
  
    // Check if the route is defined in accessControl and if the user has access
    if (accessControl[route] && accessControl[route].includes(userRole)) {
      return next();
    }
    return res.status(403).json({ message: 'Access denied' });
};

module.exports = authenticateUser;