const jwt = require("jsonwebtoken");

// Middleware to verify token and extract user role
const verifyToken = (req, res, next) => {
  const token = req.header("Authorization");

  if (!token) {
    console.log("❌ No token provided");
    return res.status(401).json({ success: false, message: "Access Denied" });
  }

  try {
    const decoded = jwt.verify(token.replace("Bearer ", ""), process.env.JWT_SECRET || "SECRET_KEY");
    req.user = decoded; // Attach user to request
    console.log("✅ Token verified - User:", decoded.id, "Role:", decoded.role);
    next();
  } catch (error) {
    console.log("❌ Token verification failed:", error.message);
    return res.status(401).json({ success: false, message: "Invalid Token" });
  }
};

// Middleware to check if user is a doctor
const isDoctor = (req, res, next) => {
  if (req.user.role !== "doctor") {
    return res.status(403).json({ success: false, message: "Access Forbidden" });
  }
  next();
};

// Middleware to check if user is an admin
const isAdmin = (req, res, next) => {
  console.log("🔍 Admin check - User role:", req.user.role, "User ID:", req.user.id);
  
  // Temporary bypass for development - remove this in production
  if (process.env.NODE_ENV === 'development' && req.user.role === 'doctor') {
    console.log("🚧 DEV MODE: Allowing doctor role to access admin endpoints");
    return next();
  }
  
  if (req.user.role !== "admin") {
    return res.status(403).json({ 
      success: false, 
      message: "Access Forbidden - Admin role required",
      userRole: req.user.role,
      debug: "Expected role: admin, got: " + req.user.role
    });
  }
  next();
};

// Middleware to check if user is a normal user
const isUser = (req, res, next) => {
  if (req.user.role !== "user") {
    return res.status(403).json({ success: false, message: "Access Forbidden" });
  }
  next();
};

module.exports = { verifyToken, isDoctor, isAdmin, isUser };
