"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.buildNewAlert = void 0;
var _deepmerge = _interopRequireDefault(require("deepmerge"));
var _lodash = require("lodash");
var _ruleDataUtils = require("@kbn/rule-data-utils");
var _strip_framework_fields = require("./strip_framework_fields");
var _nanos_to_micros = require("./nanos_to_micros");
/*
 * 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.
 */

/**
 * Builds a new alert document from the LegacyAlert class
 * Currently only populates framework fields and not any rule type specific fields
 */

const buildNewAlert = ({
  legacyAlert,
  rule,
  timestamp,
  payload,
  kibanaVersion
}) => {
  var _legacyAlert$getSched, _ref, _rule$ALERT_RULE_TAGS;
  const cleanedPayload = (0, _strip_framework_fields.stripFrameworkFields)(payload);
  return _deepmerge.default.all([cleanedPayload, rule, {
    [_ruleDataUtils.TIMESTAMP]: timestamp,
    [_ruleDataUtils.EVENT_ACTION]: 'open',
    [_ruleDataUtils.EVENT_KIND]: 'signal',
    [_ruleDataUtils.ALERT_ACTION_GROUP]: (_legacyAlert$getSched = legacyAlert.getScheduledActionOptions()) === null || _legacyAlert$getSched === void 0 ? void 0 : _legacyAlert$getSched.actionGroup,
    [_ruleDataUtils.ALERT_FLAPPING]: legacyAlert.getFlapping(),
    [_ruleDataUtils.ALERT_FLAPPING_HISTORY]: legacyAlert.getFlappingHistory(),
    [_ruleDataUtils.ALERT_INSTANCE_ID]: legacyAlert.getId(),
    [_ruleDataUtils.ALERT_MAINTENANCE_WINDOW_IDS]: legacyAlert.getMaintenanceWindowIds(),
    [_ruleDataUtils.ALERT_STATUS]: 'active',
    [_ruleDataUtils.ALERT_UUID]: legacyAlert.getUuid(),
    [_ruleDataUtils.ALERT_WORKFLOW_STATUS]: (0, _lodash.get)(cleanedPayload, _ruleDataUtils.ALERT_WORKFLOW_STATUS, 'open'),
    ...(legacyAlert.getState().duration ? {
      [_ruleDataUtils.ALERT_DURATION]: (0, _nanos_to_micros.nanosToMicros)(legacyAlert.getState().duration)
    } : {}),
    ...(legacyAlert.getState().start ? {
      [_ruleDataUtils.ALERT_START]: legacyAlert.getState().start,
      [_ruleDataUtils.ALERT_TIME_RANGE]: {
        gte: legacyAlert.getState().start
      }
    } : {}),
    [_ruleDataUtils.SPACE_IDS]: rule[_ruleDataUtils.SPACE_IDS],
    [_ruleDataUtils.VERSION]: kibanaVersion,
    [_ruleDataUtils.TAGS]: Array.from(new Set([...((_ref = cleanedPayload === null || cleanedPayload === void 0 ? void 0 : cleanedPayload.tags) !== null && _ref !== void 0 ? _ref : []), ...((_rule$ALERT_RULE_TAGS = rule[_ruleDataUtils.ALERT_RULE_TAGS]) !== null && _rule$ALERT_RULE_TAGS !== void 0 ? _rule$ALERT_RULE_TAGS : [])]))
  }], {
    arrayMerge: (_, sourceArray) => sourceArray
  });
};
exports.buildNewAlert = buildNewAlert;