/**
 * VSSTA Integration Middleware
 * Fails closed if the env var is missing or empty, and strictly compares header.
 */
const vsstaIntegrationMiddleware = (req, res, next) => {
  const secret = process.env.VSSTA_INTEGRATION_SECRET;
  if (typeof secret !== "string" || secret.length === 0) {
    return res.status(500).send("Server misconfiguration");
  }

  const headerValue = req.headers["vssta-integration-secret"];
  if (typeof headerValue !== "string" || headerValue.trim() !== secret) {
    return res.status(401).send("Unauthorized");
  }

  req.isVsstaIntegrationAuthorized = true;
  next();
};

module.exports = vsstaIntegrationMiddleware;
