const jwt = require('jsonwebtoken');

const verifyToken = (req, res, next) => {
    const authHeader = req.headers['authorization'];
    
    // Check if header exists and format is "Bearer <token>"
    if (!authHeader) {
        return res.status(403).json({ error: "Access denied. No token provided." });
    }

    const token = authHeader.split(' ')[1]; // Get token part

    if (!token) {
        return res.status(403).json({ error: "Access denied. Malformed token." });
    }

    try {
        const verified = jwt.verify(token, process.env.JWT_SECRET);
        req.user = verified; // Attach user info to request
        next(); // Proceed to route
    } catch (error) {
        res.status(401).json({ error: "Invalid token" });
    }
};

module.exports = verifyToken;
