"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getServiceGroupAlerts = getServiceGroupAlerts;
var _server = require("@kbn/observability-plugin/server");
var _ruleDataUtils = require("@kbn/rule-data-utils");
/*
 * 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 getServiceGroupAlerts({
  serviceGroups,
  apmAlertsClient,
  context,
  logger,
  spaceId
}) {
  var _result$aggregations$, _result$aggregations;
  if (!spaceId || serviceGroups.length === 0) {
    return {};
  }
  const serviceGroupsKueryMap = serviceGroups.reduce((acc, sg) => {
    acc[sg.id] = (0, _server.kqlQuery)(sg.kuery)[0];
    return acc;
  }, {});
  const params = {
    size: 0,
    track_total_hits: false,
    query: {
      bool: {
        filter: [{
          term: {
            [_ruleDataUtils.ALERT_RULE_PRODUCER]: 'apm'
          }
        }, {
          term: {
            [_ruleDataUtils.ALERT_STATUS]: 'active'
          }
        }]
      }
    },
    aggs: {
      service_groups: {
        filters: {
          filters: serviceGroupsKueryMap
        },
        aggs: {
          alerts_count: {
            cardinality: {
              field: 'kibana.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.service_groups.buckets) !== null && _result$aggregations$ !== void 0 ? _result$aggregations$ : {};
  const serviceGroupAlertsCount = Object.keys(filterAggBuckets).reduce((acc, serviceGroupId) => {
    acc[serviceGroupId] = filterAggBuckets[serviceGroupId].alerts_count.value;
    return acc;
  }, {});
  return serviceGroupAlertsCount;
}