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

// Protect routes (check token + verify user)
exports.protect = async (req, res, next) => {
  let token;

  // Check if Authorization header is present
  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith("Bearer")
  ) {
    token = req.headers.authorization.split(" ")[1]; // Get token from "Bearer <token>"
  }

  // If no token found
  if (!token) {
    return res.status(401).json({
      success: false,
      error: "Not authorized, no token provided",
    });
  }

  try {
    // Verify token
    const decoded = jwt.verify(token, process.env.JWT_SECRET);

    // Attach user to request (without password)
    req.user = await User.findById(decoded.id).select("-password");

    if (!req.user) {
      return res.status(401).json({
        success: false,
        error: "User not found",
      });
    }

    next(); // Continue to route handler
  } catch (err) {
    console.error("JWT Error:", err.message);
    return res.status(401).json({
      success: false,
      error: "Not authorized, token failed or expired",
    });
  }
};

// Role-based authorization (only specific roles can access)
exports.authorize = (...roles) => {
  return (req, res, next) => {
    if (!roles.includes(req.user.role)) {
      return res.status(403).json({
        success: false,
        error: `User role '${req.user.role}' is not authorized to access this route`,
      });
    }
    next();
  };
};
