const Jwt = require('jsonwebtoken');

const adminauthMiddleware = async(req, res, next)=>{
    // get info
    const token = req.header('Authorization');
    // let's check token is get or not
    if(!token){
        return res.status(400).json({message: 'Cannot get Token, Unauthorized Http'})
    }
    
    // verify token
    try{
        const isVerified = Jwt.verify(token, process.env.JWT_SECRET_USER);
        if(isVerified){
            // get data
            const userid = isVerified.id;
            const name = isVerified.name;
            const phone = isVerified.phone;
            req.token = token;
            req.userid = userid;
            req.name = name;
            req.phone = phone;
            next();
        }else{
            res.status(401).json({message: 'Invalid token'});
        }
    }catch(err){
        res.status(402).json({message: 'Unauthorized token!'});
    }
}

module.exports = adminauthMiddleware;