(function nativeObservabilityAjaxCorrelationBehavior(
  Drupal,
  drupalSettings,
  once,
  $,
) {
  /**
   * Adds the current (page) request id as a parent id header to every AJAX call.
   *
   * This enables parent/child correlation between:
   * - the HTML page request (parent)
   * - subsequent Drupal AJAX requests (children)
   *
   * MVP scope:
   * - Drupal AJAX is jQuery-based, so ajaxPrefilter is enough for most cases.
   * - This must never break requests (fail-safe).
   */
  Drupal.behaviors.nativeObservabilityAjaxCorrelation = {
    attach(context) {
      once('native-observability-ajax-correlation', 'html', context).forEach(
        function initAjaxCorrelation() {
          const cfg = drupalSettings.nativeObservability || {};
          const parentRequestId = cfg.requestId || '';

          if (!parentRequestId) {
            return;
          }

          // Add header to every jQuery AJAX request (Drupal AJAX uses jQuery).
          $.ajaxPrefilter(
            function addNativeObservabilityParentHeader(
              options,
              originalOptions,
              jqXHR,
            ) {
              try {
                jqXHR.setRequestHeader(
                  'X-Native-Observability-Parent-Request-Id',
                  parentRequestId,
                );
              } catch (e) {
                // Never break the request pipeline.
              }
            },
          );
        },
      );
    },
  };
})(Drupal, drupalSettings, once, jQuery);
