// this middleware is helping us to protect our routes so that only authenticated users can access the routes
//it is checking if the user is authenticated by checking the token in the header(the header is the part of the request that contains the token)
//if the user is not authenticated, it will return a 401 status code and a message that the user is not authorized
//if the user is authenticated, it will return the user object
//and the user object is the user that is authenticated

const jwt = require('jsonwebtoken');
const User = require('../models/User');
const JWT_SECRET = 'change_this_to_a_long_random_secret';

exports.protect = async (req, res, next) => {
  try {
    const header = req.headers.authorization;

    if (!header || !header.startsWith('Bearer ')) {
      return res.status(401).json({ message: 'Not authorized' });
    }

    const token = header.split(' ')[1];
    const decoded = jwt.verify(token, JWT_SECRET);
    const user = await User.findById(decoded.userId).select('-password');

    if (!user) {
      return res.status(401).json({ message: 'Not authorized' });
    }

    req.user = user;
    next();
  } catch (err) {
    return res.status(401).json({ message: 'Not authorized' });
  }
};
