"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.aggregateRulesRoute = void 0;
var _aggregate = require("../../../../application/rule/methods/aggregate");
var _lib = require("../../../lib");
var _types = require("../../../../types");
var _track_legacy_terminology = require("../../../lib/track_legacy_terminology");
var _aggregate2 = require("../../../../../common/routes/rule/apis/aggregate");
var _transforms = require("./transforms");
/*
 * 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 aggregateRulesRoute = (router, licenseState, usageCounter) => {
  router.post({
    path: `${_types.INTERNAL_BASE_ALERTING_API_PATH}/rules/_aggregate`,
    validate: {
      body: _aggregate2.aggregateRulesRequestBodySchemaV1
    }
  }, router.handleLegacyErrors((0, _lib.verifyAccessAndContext)(licenseState, async function (context, req, res) {
    const rulesClient = (await context.alerting).getRulesClient();
    const body = req.body;
    const options = (0, _transforms.transformAggregateQueryRequestV1)({
      ...body,
      has_reference: body.has_reference || undefined
    });
    (0, _track_legacy_terminology.trackLegacyTerminology)([body.search, body.search_fields].filter(Boolean), usageCounter);
    const aggregateResult = await rulesClient.aggregate({
      aggs: (0, _aggregate.defaultRuleAggregationFactoryV1)(),
      options
    });
    const responsePayload = {
      body: (0, _transforms.transformAggregateBodyResponseV1)((0, _transforms.formatDefaultAggregationResult)(aggregateResult))
    };
    return res.ok(responsePayload);
  })));
};
exports.aggregateRulesRoute = aggregateRulesRoute;