"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getFakeKibanaRequest = getFakeKibanaRequest;
exports.getRuleAttributes = getRuleAttributes;
exports.validateRule = validateRule;
var _server = require("@kbn/spaces-plugin/server");
var _server2 = require("@kbn/core/server");
var _lib = require("../lib");
var _types = require("../types");
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.
 */

function validateRule(params) {
  if (params.ruleData.error) {
    throw params.ruleData.error;
  }
  const {
    ruleData: {
      data: {
        indirectParams,
        rule,
        fakeRequest,
        rulesClient,
        version
      }
    },
    ruleTypeRegistry,
    paramValidator,
    alertingEventLogger
  } = params;
  const {
    enabled,
    apiKey
  } = indirectParams;
  if (!enabled) {
    throw new _lib.ErrorWithReason(_types.RuleExecutionStatusErrorReasons.Disabled, new Error(`Rule failed to execute because rule ran after it was disabled.`));
  }
  alertingEventLogger.setRuleName(rule.name);
  try {
    ruleTypeRegistry.ensureRuleTypeEnabled(rule.alertTypeId);
  } catch (err) {
    throw new _lib.ErrorWithReason(_types.RuleExecutionStatusErrorReasons.License, err);
  }
  let validatedParams;
  try {
    validatedParams = (0, _lib.validateRuleTypeParams)(rule.params, paramValidator);
  } catch (err) {
    throw new _lib.ErrorWithReason(_types.RuleExecutionStatusErrorReasons.Validate, err);
  }
  if (rule.monitoring) {
    if (rule.monitoring.run.history.length >= _common.MONITORING_HISTORY_LIMIT) {
      // Remove the first (oldest) record
      rule.monitoring.run.history.shift();
    }
  }
  return {
    rule,
    indirectParams,
    fakeRequest,
    apiKey,
    rulesClient,
    validatedParams,
    version
  };
}
async function getRuleAttributes(context, ruleId, spaceId) {
  const namespace = context.spaceIdToNamespace(spaceId);
  const rawRule = await context.encryptedSavedObjectsClient.getDecryptedAsInternalUser('alert', ruleId, {
    namespace
  });
  const fakeRequest = getFakeKibanaRequest(context, spaceId, rawRule.attributes.apiKey);
  const rulesClient = context.getRulesClientWithRequest(fakeRequest);
  const rule = rulesClient.getAlertFromRaw({
    id: ruleId,
    ruleTypeId: rawRule.attributes.alertTypeId,
    rawRule: rawRule.attributes,
    references: rawRule.references,
    includeLegacyId: false,
    omitGeneratedValues: false
  });
  return {
    rule,
    version: rawRule.version,
    indirectParams: rawRule.attributes,
    fakeRequest,
    rulesClient
  };
}
function getFakeKibanaRequest(context, spaceId, apiKey) {
  const requestHeaders = {};
  if (apiKey) {
    requestHeaders.authorization = `ApiKey ${apiKey}`;
  }
  const path = (0, _server.addSpaceIdToPath)('/', spaceId);
  const fakeRawRequest = {
    headers: requestHeaders,
    path: '/'
  };
  const fakeRequest = _server2.CoreKibanaRequest.from(fakeRawRequest);
  context.basePathService.set(fakeRequest, path);
  return fakeRequest;
}