"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getExitSpanLatency = getExitSpanLatency;
var _server = require("@kbn/observability-plugin/server");
var _document_type = require("../../../../common/document_type");
var _apm = require("../../../../common/es_fields/apm");
var _rollup = require("../../../../common/rollup");
var _fetch_timeseries = require("./fetch_timeseries");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

async function getExitSpanLatency({
  apmEventClient,
  start,
  end,
  intervalString,
  filter,
  spanDestinationServiceResource
}) {
  return (await (0, _fetch_timeseries.fetchSeries)({
    apmEventClient,
    start,
    end,
    operationName: 'assistant_get_exit_span_latency',
    unit: 'ms',
    documentType: _document_type.ApmDocumentType.ServiceDestinationMetric,
    rollupInterval: _rollup.RollupInterval.OneMinute,
    intervalString,
    filter: filter.concat(...(0, _server.termQuery)(_apm.SPAN_DESTINATION_SERVICE_RESOURCE, spanDestinationServiceResource)),
    groupBy: _apm.SPAN_DESTINATION_SERVICE_RESOURCE,
    aggs: {
      count: {
        sum: {
          field: _apm.SPAN_DESTINATION_SERVICE_RESPONSE_TIME_COUNT
        }
      },
      latency: {
        sum: {
          field: _apm.SPAN_DESTINATION_SERVICE_RESPONSE_TIME_SUM
        }
      },
      value: {
        bucket_script: {
          buckets_path: {
            latency: 'latency',
            count: 'count'
          },
          script: '(params.latency / params.count) / 1000'
        }
      }
    }
  })).map(fetchedSerie => {
    return {
      ...fetchedSerie,
      data: fetchedSerie.data.map(bucket => {
        var _bucket$value;
        return {
          x: bucket.key,
          y: (_bucket$value = bucket.value) === null || _bucket$value === void 0 ? void 0 : _bucket$value.value
        };
      })
    };
  });
}