
// middleware/authenticate.js
const jwt = require("jsonwebtoken");

const authenticate = (req, res, next) => {
  try {
    // SESSION (Primary - since you are using sessions)
    if (req.session && req.session.user) {
      req.user = req.session.user;

      console.log("=== SESSION DEBUG ===");
      console.log("Session user:", {
        id: req.user?.id,
        // email: req.user?.email,
        orgId: req.user?.orgId,
        role: req.user?.role
      });

      if (!req.user?.orgId) {
        console.warn("WARNING: orgId is missing in session!");
      }
      return next();
    }

    // JWT Fallback
    const authHeader = req.headers.authorization;
    if (authHeader && authHeader.startsWith("Bearer ")) {
      const token = authHeader.split(" ")[1];
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      req.user = decoded;
      console.log("JWT decoded orgId:", decoded?.orgId);
      return next();
    }

    return res.status(401).json({
      success: false,
      message: "Unauthorized - No session or token"
    });
  } catch (err) {
    console.error("Authenticate error:", err.message);
    return res.status(401).json({
      success: false,
      message: "Invalid or expired session. Please re-login."
    });
  }
};

module.exports = authenticate;