"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createRuleRoute = void 0;
var _lib = require("../../../../lib");
var _lib2 = require("../../../lib");
var _types = require("../../../../types");
var _create = require("../../../../../common/routes/rule/apis/create");
var _transforms = require("./transforms");
var _transforms2 = 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 createRuleRoute = ({
  router,
  licenseState,
  usageCounter
}) => {
  router.post({
    path: `${_types.BASE_ALERTING_API_PATH}/rule/{id?}`,
    validate: {
      body: _create.createBodySchemaV1,
      params: _create.createParamsSchemaV1
    }
  }, (0, _lib2.handleDisabledApiKeysError)(router.handleLegacyErrors((0, _lib2.verifyAccessAndContext)(licenseState, async function (context, req, res) {
    const rulesClient = (await context.alerting).getRulesClient();

    // Assert versioned inputs
    const createRuleData = req.body;
    const params = req.params;
    (0, _lib2.countUsageOfPredefinedIds)({
      predefinedId: params === null || params === void 0 ? void 0 : params.id,
      spaceId: rulesClient.getSpaceId(),
      usageCounter
    });
    try {
      // TODO (http-versioning): Remove this cast, this enables us to move forward
      // without fixing all of other solution types
      const createdRule = await rulesClient.create({
        data: (0, _transforms.transformCreateBodyV1)(createRuleData),
        options: {
          id: params === null || params === void 0 ? void 0 : params.id
        }
      });

      // Assert versioned response type
      const response = {
        body: (0, _transforms2.transformRuleToRuleResponseV1)(createdRule)
      };
      return res.ok(response);
    } catch (e) {
      if (e instanceof _lib.RuleTypeDisabledError) {
        return e.sendResponse(res);
      }
      throw e;
    }
  }))));
};
exports.createRuleRoute = createRuleRoute;