const jwt = require("jsonwebtoken")

module.exports = function requireAdmin(req, res, next) {
  const authHeader = req.headers.authorization

  if (!authHeader || !authHeader.startsWith("Bearer ")) {
    return res.status(401).json({ message: "No token provided" })
  }

  const token = authHeader.split(" ")[1]

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET)
    console.log("ADMIN TOKEN DECODED:", decoded)

    if (decoded.role !== "admin") {
      return res.status(403).json({ message: "Admin access denied" })
    }

    req.admin = decoded
    next()
  } catch (err) {
    return res.status(401).json({ message: "Invalid or expired token" })
  }
}
