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

const loggedInGuest = asyncHandler ( async (req, res, next) => {
    const {guestToken} = req.body;
    console.log(guestToken);
    if(!guestToken) {
        console.log("guestToken does not exist");
        return res.status(401).json({success:false, error: "User is not authorized or access token is missing."});
        //throw new Error("User is not authorized or access token is missing.");
    }else{
        jwt.verify(guestToken, process.env.ACCESS_TOKEN_SECRET, (err, decode) => {
            if(!err) {
                req.guest = decode.user;
                console.log(req.guest);
                next();
            }else{
                console.log("there was some error "+ err);
                return res.status(401).json({success:false, error: "User is not authorized."});
                //throw new Error("User is not authorized.");
            }
        });
    }
    //next();
});

module.exports = loggedInGuest;