"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getTopVulnerableResources = void 0;
var _constants = require("../../../common/constants");
/*
 * 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 getVulnerabilitiesResourcesQuery = () => ({
  size: 0,
  query: {
    match_all: {}
  },
  index: _constants.LATEST_VULNERABILITIES_INDEX_DEFAULT_NS,
  aggs: {
    vulnerable_resources: {
      terms: {
        field: 'resource.id',
        order: {
          _count: 'desc'
        },
        size: 10
      },
      aggs: {
        resource_name: {
          terms: {
            field: 'resource.name',
            size: 1
          }
        },
        top_region: {
          terms: {
            field: 'cloud.region',
            size: 1
          }
        }
      }
    }
  }
});
const getTopVulnerableResources = async esClient => {
  var _queryResult$aggregat;
  const queryResult = await esClient.search(getVulnerabilitiesResourcesQuery());
  if (!(queryResult !== null && queryResult !== void 0 && (_queryResult$aggregat = queryResult.aggregations) !== null && _queryResult$aggregat !== void 0 && _queryResult$aggregat.vulnerable_resources)) return [];
  return queryResult.aggregations.vulnerable_resources.buckets.map(resource => {
    var _resource$resource_na, _resource$resource_na2, _resource$resource_na3, _resource$resource_na4, _resource$top_region$, _resource$top_region, _resource$top_region$2, _resource$top_region$3;
    return {
      resource: {
        id: resource.key,
        name: (_resource$resource_na = (_resource$resource_na2 = resource.resource_name) === null || _resource$resource_na2 === void 0 ? void 0 : (_resource$resource_na3 = _resource$resource_na2.buckets) === null || _resource$resource_na3 === void 0 ? void 0 : (_resource$resource_na4 = _resource$resource_na3[0]) === null || _resource$resource_na4 === void 0 ? void 0 : _resource$resource_na4.key) !== null && _resource$resource_na !== void 0 ? _resource$resource_na : ''
      },
      vulnerabilityCount: resource.doc_count,
      cloudRegion: (_resource$top_region$ = (_resource$top_region = resource.top_region) === null || _resource$top_region === void 0 ? void 0 : (_resource$top_region$2 = _resource$top_region.buckets) === null || _resource$top_region$2 === void 0 ? void 0 : (_resource$top_region$3 = _resource$top_region$2[0]) === null || _resource$top_region$3 === void 0 ? void 0 : _resource$top_region$3.key) !== null && _resource$top_region$ !== void 0 ? _resource$top_region$ : ''
    };
  });
};
exports.getTopVulnerableResources = getTopVulnerableResources;