"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getAgentCountForAgentPolicies = void 0;
var _common = require("../../../common");
/*
 * 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.
 */

/**
 * Given a list of Agent Policy IDs, an object will be returned with the agent policy id as the key
 * and the number of active agents using that agent policy.
 * @param esClient
 * @param agentPolicyIds
 */
const getAgentCountForAgentPolicies = async (esClient, agentPolicyIds) => {
  var _searchResponse$aggre;
  if (agentPolicyIds.length === 0) {
    return {};
  }
  const searchPromise = esClient.search({
    index: _common.AGENTS_INDEX,
    ignore_unavailable: true,
    body: {
      query: {
        bool: {
          filter: [{
            term: {
              active: 'true'
            }
          }, {
            terms: {
              policy_id: agentPolicyIds
            }
          }]
        }
      },
      aggs: {
        agent_counts: {
          terms: {
            field: 'policy_id',
            size: agentPolicyIds.length
          }
        }
      },
      size: 0
    }
  });
  const response = agentPolicyIds.reduce((acc, agentPolicyId) => {
    acc[agentPolicyId] = 0;
    return acc;
  }, {});
  const searchResponse = await searchPromise;
  if ((_searchResponse$aggre = searchResponse.aggregations) !== null && _searchResponse$aggre !== void 0 && _searchResponse$aggre.agent_counts.buckets) {
    var _searchResponse$aggre2;
    const buckets = (_searchResponse$aggre2 = searchResponse.aggregations) === null || _searchResponse$aggre2 === void 0 ? void 0 : _searchResponse$aggre2.agent_counts.buckets;
    for (const {
      key: agentPolicyId,
      doc_count: count
    } of buckets) {
      response[agentPolicyId] = count;
    }
  }
  return response;
};
exports.getAgentCountForAgentPolicies = getAgentCountForAgentPolicies;