const jwt = require("jsonwebtoken");
const secret = "bobros";


const jwtAuthorization = (req, res, next) => {
    console.log("jwt verification started");
    console.log("Headers received:", req.headers);
    try {
        const accessToken = req.cookies || req.headers.authorization?.replace("Bearer", "").trim();
        console.log(accessToken);
        if(!accessToken) {
            return res.status(401).json({msg: "accessToken is not available"})
        }

        const decodedHeader = jwt.decode(accessToken, { complete: true });
        const clientId = decodedHeader.payload;
        console.log(clientId);
        
        const clientDetail = jwt.verify(accessToken, secret, (error, payload) => {
           if (error) {
            return res.status(401).json({msg:"Invalid access Token"})
           } 
           else {
            console.log("jwt verified successfully");
            req.client = clientDetail.payload.name
        }}
    )
    } catch (error) {
        console.log(error)
    }
        next();
};



module.exports = jwtAuthorization