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

const validateToken = asyncHandler(async (req, res, next) => {
    console.log("Inside validateToken");

    let token;
    let authHeader = req.headers.authorization || req.headers.Authorization;
    if (authHeader && authHeader.startsWith("Bearer")) {
        token = authHeader.split(" ")[1];
        console.log("Using Authorization Token:", token);

        try {
            const decode = jwt.verify(token, process.env.ACCESS_TOKEN_SECRET);

            console.log("Token decoded successfully:", decode);
            req.user = decode.user || decode;  
            req.guest = decode.user || decode; 
            return next();
        } catch (err) {
            console.log("Authorization token invalid:", err.message);
        }
    }

    if (req.body.guestToken) {
        console.log("Using guestToken:", req.body.guestToken);

        try {
            const decode = jwt.verify(req.body.guestToken, process.env.ACCESS_TOKEN_SECRET);

            console.log("Guest token decoded successfully:", decode);
            req.user = decode.user || decode;
            req.guest = decode.user || decode;
            req.guestToken = req.body.guestToken;

            return next();
        } catch (err) {
            console.log("Guest token invalid:", err.message);
        }
    }
    console.log("No valid token provided");
    res.status(401);
    throw new Error("User is not authorized or token is missing.");
});

module.exports = validateToken;
