import jwt from 'jsonwebtoken';
import User from '../models/userModel.js';


export const protect = async(req, res, next) =>{
    console.log("PROTECT HIT");
    console.log("AUTH HEADER:", req.headers.authorization);
    let token;

    if(req.headers.authorization && req.headers.authorization.startsWith('Bearer')){
        try {
            token = req.headers.authorization.split(' ')[1];
            const decoded = jwt.verify(token, process.env.JWT_TOKEN);
            req.user = await User.findById(decoded.id).select('-password');
            next();   
        } catch (err) {
            console.log(err);
            res.status(401).json({message:"Not Authorized ,Token Failed"}); 
        }
    } else{
        res.status(401).json({message:"Not Authoriaed, No token "})
    }
}
