const jwt = require('jsonwebtoken');

exports.verifyToken = (req, res, next) => {
    console.log("1. Midleware: Memulai Cek Token");

    if(!req.headers) {
        return res.status(400).json({msg: "Header request tidak ditemukan/kosong"});
    }
    
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if(token == null){
     console.log("Token Kosong");   
     return res.sendStatus(401);
    }

    jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
        if(err){
        console.log("TOken Salah / Expired");
        return res.sendStatus(403);
        }

        console.log("Token Valid User", decoded.email);
        req.email = decoded.email;
        req.userId = decoded.userId;

        next();
    });
}