"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getServicesAlerts = getServicesAlerts;
var _server = require("@kbn/observability-plugin/server");
var _ruleDataUtils = require("@kbn/rule-data-utils");
var _apm = require("../../../../common/es_fields/apm");
var _environment_query = require("../../../../common/utils/environment_query");
var _get_services_items = require("./get_services_items");
var _service_group_query_with_overflow = require("../../../lib/service_group_query_with_overflow");
/*
 * 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 getServicesAlerts({
  apmAlertsClient,
  kuery,
  maxNumServices = _get_services_items.MAX_NUMBER_OF_SERVICES,
  serviceGroup,
  serviceName,
  start,
  end,
  environment
}) {
  var _result$aggregations$, _result$aggregations;
  const params = {
    size: 0,
    track_total_hits: false,
    query: {
      bool: {
        filter: [...(0, _server.termQuery)(_ruleDataUtils.ALERT_RULE_PRODUCER, 'apm'), ...(0, _server.termQuery)(_ruleDataUtils.ALERT_STATUS, _ruleDataUtils.ALERT_STATUS_ACTIVE), ...(0, _server.rangeQuery)(start, end), ...(0, _server.kqlQuery)(kuery), ...(0, _service_group_query_with_overflow.serviceGroupWithOverflowQuery)(serviceGroup), ...(0, _server.termQuery)(_apm.SERVICE_NAME, serviceName), ...(0, _environment_query.environmentQuery)(environment)]
      }
    },
    aggs: {
      services: {
        terms: {
          field: _apm.SERVICE_NAME,
          size: maxNumServices
        },
        aggs: {
          alerts_count: {
            cardinality: {
              field: _ruleDataUtils.ALERT_UUID
            }
          }
        }
      }
    }
  };
  const result = await apmAlertsClient.search(params);
  const filterAggBuckets = (_result$aggregations$ = (_result$aggregations = result.aggregations) === null || _result$aggregations === void 0 ? void 0 : _result$aggregations.services.buckets) !== null && _result$aggregations$ !== void 0 ? _result$aggregations$ : [];
  const servicesAlertsCount = filterAggBuckets.map(bucket => ({
    serviceName: bucket.key,
    alertsCount: bucket.alerts_count.value
  }));
  return servicesAlertsCount;
}