"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.resolve = resolve;
var _ruleDataUtils = require("@kbn/rule-data-utils");
var _authorization = require("../../authorization");
var _audit_events = require("../common/audit_events");
var _get_alert_from_raw = require("../lib/get_alert_from_raw");
var _lib = require("../lib");
/*
 * 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.
 */

async function resolve(context, {
  id,
  includeLegacyId,
  includeSnoozeData = false
}) {
  var _context$auditLogger2;
  const {
    saved_object: result,
    ...resolveResponse
  } = await context.unsecuredSavedObjectsClient.resolve('alert', id);
  try {
    await context.authorization.ensureAuthorized({
      ruleTypeId: result.attributes.alertTypeId,
      consumer: result.attributes.consumer,
      operation: _authorization.ReadOperations.Get,
      entity: _authorization.AlertingAuthorizationEntity.Rule
    });
  } catch (error) {
    var _context$auditLogger;
    (_context$auditLogger = context.auditLogger) === null || _context$auditLogger === void 0 ? void 0 : _context$auditLogger.log((0, _audit_events.ruleAuditEvent)({
      action: _audit_events.RuleAuditAction.RESOLVE,
      savedObject: {
        type: 'alert',
        id
      },
      error
    }));
    throw error;
  }
  (_context$auditLogger2 = context.auditLogger) === null || _context$auditLogger2 === void 0 ? void 0 : _context$auditLogger2.log((0, _audit_events.ruleAuditEvent)({
    action: _audit_events.RuleAuditAction.RESOLVE,
    savedObject: {
      type: 'alert',
      id
    }
  }));
  const rule = (0, _get_alert_from_raw.getAlertFromRaw)(context, result.id, result.attributes.alertTypeId, result.attributes, result.references, includeLegacyId, false, includeSnoozeData);

  // format legacy actions for SIEM rules
  if (result.attributes.consumer === _ruleDataUtils.AlertConsumers.SIEM) {
    const [migratedRule] = await (0, _lib.formatLegacyActions)([rule], {
      savedObjectsClient: context.unsecuredSavedObjectsClient,
      logger: context.logger
    });
    return {
      ...migratedRule,
      ...resolveResponse
    };
  }
  return {
    ...rule,
    ...resolveResponse
  };
}