"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getStatsFromFindingsEvaluationsAggs = exports.getStats = exports.getEvaluationsQuery = exports.findingsEvaluationAggsQuery = void 0;
var _helpers = require("../../../common/utils/helpers");
/*
 * 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 findingsEvaluationAggsQuery = {
  failed_findings: {
    filter: {
      term: {
        'result.evaluation': 'failed'
      }
    }
  },
  passed_findings: {
    filter: {
      term: {
        'result.evaluation': 'passed'
      }
    }
  }
};
exports.findingsEvaluationAggsQuery = findingsEvaluationAggsQuery;
const uniqueResourcesCountQuery = {
  resources_evaluated: {
    cardinality: {
      field: 'resource.id'
    }
  }
};
const getEvaluationsQuery = (query, pitId, runtimeMappings) => ({
  size: 0,
  // creates the `safe_posture_type` runtime fields,
  // `safe_posture_type` is used by the `query` to filter by posture type for older findings without this field
  runtime_mappings: runtimeMappings,
  query,
  aggs: {
    ...findingsEvaluationAggsQuery,
    ...uniqueResourcesCountQuery
  },
  pit: {
    id: pitId
  }
});
exports.getEvaluationsQuery = getEvaluationsQuery;
const getStatsFromFindingsEvaluationsAggs = findingsEvaluationsAggs => {
  var _findingsEvaluationsA;
  const resourcesEvaluated = (_findingsEvaluationsA = findingsEvaluationsAggs.resources_evaluated) === null || _findingsEvaluationsA === void 0 ? void 0 : _findingsEvaluationsA.value;
  const failedFindings = findingsEvaluationsAggs.failed_findings.doc_count || 0;
  const passedFindings = findingsEvaluationsAggs.passed_findings.doc_count || 0;
  const totalFindings = failedFindings + passedFindings;
  const postureScore = (0, _helpers.calculatePostureScore)(passedFindings, failedFindings) || 0;
  return {
    totalFailed: failedFindings,
    totalPassed: passedFindings,
    totalFindings,
    postureScore,
    ...(resourcesEvaluated && {
      resourcesEvaluated
    })
  };
};
exports.getStatsFromFindingsEvaluationsAggs = getStatsFromFindingsEvaluationsAggs;
const getStats = async (esClient, query, pitId, runtimeMappings) => {
  const evaluationsQueryResult = await esClient.search(getEvaluationsQuery(query, pitId, runtimeMappings));
  const findingsEvaluations = evaluationsQueryResult.aggregations;
  if (!findingsEvaluations) throw new Error('missing findings evaluations');
  return getStatsFromFindingsEvaluationsAggs(findingsEvaluations);
};
exports.getStats = getStats;