"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.injectReferencesIntoActions = injectReferencesIntoActions;
exports.injectReferencesIntoParams = injectReferencesIntoParams;
var _boom = _interopRequireDefault(require("@hapi/boom"));
var _lodash = require("lodash");
var _constants = require("./constants");
/*
 * 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 injectReferencesIntoActions(alertId, actions, references) {
  return actions.map(action => {
    if (action.actionRef.startsWith(_constants.preconfiguredConnectorActionRefPrefix)) {
      return {
        ...(0, _lodash.omit)(action, 'actionRef'),
        id: action.actionRef.replace(_constants.preconfiguredConnectorActionRefPrefix, '')
      };
    }
    if (action.actionRef.startsWith(_constants.systemConnectorActionRefPrefix)) {
      return {
        ...(0, _lodash.omit)(action, 'actionRef'),
        id: action.actionRef.replace(_constants.systemConnectorActionRefPrefix, '')
      };
    }
    const reference = references.find(ref => ref.name === action.actionRef);
    if (!reference) {
      throw new Error(`Action reference "${action.actionRef}" not found in alert id: ${alertId}`);
    }
    return {
      ...(0, _lodash.omit)(action, 'actionRef'),
      id: reference.id
    };
  });
}
function injectReferencesIntoParams(ruleId, ruleType, ruleParams, references) {
  try {
    var _ruleType$useSavedObj;
    const paramReferences = references.filter(reference => reference.name.startsWith(_constants.extractedSavedObjectParamReferenceNamePrefix)).map(reference => ({
      ...reference,
      name: reference.name.replace(_constants.extractedSavedObjectParamReferenceNamePrefix, '')
    }));
    return ruleParams && ruleType !== null && ruleType !== void 0 && (_ruleType$useSavedObj = ruleType.useSavedObjectReferences) !== null && _ruleType$useSavedObj !== void 0 && _ruleType$useSavedObj.injectReferences ? ruleType.useSavedObjectReferences.injectReferences(ruleParams, paramReferences) : ruleParams;
  } catch (err) {
    throw _boom.default.badRequest(`Error injecting reference into rule params for rule id ${ruleId} - ${err.message}`);
  }
}