"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.calculateFailedTransactionRate = calculateFailedTransactionRate;
exports.getFailedTransactionRateTimeSeries = getFailedTransactionRateTimeSeries;
exports.getOutcomeAggregation = void 0;
var _document_type = require("../../../common/document_type");
var _apm = require("../../../common/es_fields/apm");
var _event_outcome = require("../../../common/event_outcome");
/*
 * 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.
 */

const getOutcomeAggregation = documentType => {
  if (documentType === _document_type.ApmDocumentType.ServiceTransactionMetric) {
    return {
      successful_or_failed: {
        value_count: {
          field: _apm.EVENT_SUCCESS_COUNT
        }
      },
      successful: {
        sum: {
          field: _apm.EVENT_SUCCESS_COUNT
        }
      }
    };
  }
  return {
    successful_or_failed: {
      filter: {
        bool: {
          filter: [{
            terms: {
              [_apm.EVENT_OUTCOME]: [_event_outcome.EventOutcome.failure, _event_outcome.EventOutcome.success]
            }
          }]
        }
      }
    },
    successful: {
      filter: {
        bool: {
          filter: [{
            terms: {
              [_apm.EVENT_OUTCOME]: [_event_outcome.EventOutcome.success]
            }
          }]
        }
      }
    }
  };
};
exports.getOutcomeAggregation = getOutcomeAggregation;
function calculateFailedTransactionRate(outcomeResponse) {
  var _outcomeResponse$succ;
  const successfulTransactions = 'value' in outcomeResponse.successful ? (_outcomeResponse$succ = outcomeResponse.successful.value) !== null && _outcomeResponse$succ !== void 0 ? _outcomeResponse$succ : 0 : outcomeResponse.successful.doc_count;
  const successfulOrFailedTransactions = 'value' in outcomeResponse.successful_or_failed ? outcomeResponse.successful_or_failed.value : outcomeResponse.successful_or_failed.doc_count;
  const failedTransactions = successfulOrFailedTransactions - successfulTransactions;
  return failedTransactions / successfulOrFailedTransactions;
}
function getFailedTransactionRateTimeSeries(buckets) {
  return buckets.map(dateBucket => {
    return {
      x: dateBucket.key,
      y: calculateFailedTransactionRate(dateBucket)
    };
  });
}