/**
 * Middleware to check if the request is authorized for Parts Management Integration.
 * @param req
 * @param res
 * @param next
 * @returns {*}
 */
const partsManagementIntegrationMiddleware = (req, res, next) => {
  const secret = process.env.PARTS_MANAGEMENT_INTEGRATION_SECRET;
  if (typeof secret !== "string" || secret.length === 0) {
    return res.status(500).send("Server misconfiguration");
  }

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

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

module.exports = partsManagementIntegrationMiddleware;
