const jwt = require("jsonwebtoken");

/**
 * SSE Authentication Middleware
 * Supports token from query string (for SSE connections) or Authorization header
 */
module.exports = function (req, res, next) {
  let token;

  // Try to get token from query string (for SSE EventSource connections)
  if (req.query.token) {
    token = req.query.token;
  }
  // Try to get token from Authorization header (Bearer token)
  else if (req.headers.authorization && req.headers.authorization.startsWith("Bearer ")) {
    token = req.headers.authorization.substring(7);
  }
  // Try to get token from x-auth-token header (legacy support)
  else if (req.header("x-auth-token")) {
    token = req.header("x-auth-token");
  }

  // Check if no token found
  if (!token) {
    return res.status(401).json({ 
      success: false, 
      msg: "No token, authorization denied" 
    });
  }

  // Verify token
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded.user;
    next();
  } catch (err) {
    return res.status(401).json({ 
      success: false, 
      msg: "Token is not valid" 
    });
  }
};
