// middleware/auth.js
const jwt  = require('jsonwebtoken');
const User = require('../models/User');

// Protect routes: require valid token
exports.protect = async (req, res, next) => {
  let token;
  if (req.headers.authorization?.startsWith('Bearer ')) {
    token = req.headers.authorization.split(' ')[1];
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      // Attach user document (minus password) to req.user
      req.user = await User.findById(decoded.id).select('-password');
      return next();
    } catch (error) {
      console.error('Token verification failed:', error);
      return res.status(401).json({ message: 'Not authorized, token failed' });
    }
  }
  res.status(401).json({ message: 'Not authorized, no token' });
};

// Admin-only middleware
exports.admin = (req, res, next) => {
  if (req.user?.admin) {
    return next();
  }
  res.status(403).json({ message: 'Not authorized as an admin' });
};