"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getTransactionFailureRate = getTransactionFailureRate;
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 _transaction_error_rate = require("../../../lib/helpers/transaction_error_rate");
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 getTransactionFailureRate({
  apmEventClient,
  start,
  end,
  intervalString,
  filter,
  transactionType
}) {
  return (await (0, _fetch_timeseries.fetchSeries)({
    apmEventClient,
    start,
    end,
    operationName: 'assistant_get_transaction_failure_rate',
    unit: '%',
    documentType: _document_type.ApmDocumentType.TransactionMetric,
    rollupInterval: _rollup.RollupInterval.OneMinute,
    intervalString,
    filter: filter.concat(...(0, _server.termQuery)(_apm.TRANSACTION_TYPE, transactionType)),
    groupBy: 'transaction.type',
    aggs: {
      ...(0, _transaction_error_rate.getOutcomeAggregation)(_document_type.ApmDocumentType.TransactionMetric),
      value: {
        bucket_script: {
          buckets_path: {
            successful_or_failed: 'successful_or_failed>_count',
            successful: 'successful>_count'
          },
          script: '100 * (1 - (params.successful / params.successful_or_failed))'
        }
      }
    }
  })).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
        };
      })
    };
  });
}