"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.muteInstance = muteInstance;
var _boom = _interopRequireDefault(require("@hapi/boom"));
var _update_rule_so = require("../../../../data/rule/methods/update_rule_so");
var _schemas = require("./schemas");
var _authorization = require("../../../../authorization");
var _retry_if_conflicts = require("../../../../lib/retry_if_conflicts");
var _audit_events = require("../../../../rules_client/common/audit_events");
var _lib = require("../../../../rules_client/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 muteInstance(context, params) {
  try {
    _schemas.muteAlertParamsSchema.validate(params);
  } catch (error) {
    throw _boom.default.badRequest(`Failed to validate params: ${error.message}`);
  }
  return await (0, _retry_if_conflicts.retryIfConflicts)(context.logger, `rulesClient.muteInstance('${params.alertId}')`, async () => await muteInstanceWithOCC(context, params));
}
async function muteInstanceWithOCC(context, {
  alertId,
  alertInstanceId
}) {
  var _context$auditLogger2;
  const {
    attributes,
    version
  } = await context.unsecuredSavedObjectsClient.get('alert', alertId);
  try {
    await context.authorization.ensureAuthorized({
      ruleTypeId: attributes.alertTypeId,
      consumer: attributes.consumer,
      operation: _authorization.WriteOperations.MuteAlert,
      entity: _authorization.AlertingAuthorizationEntity.Rule
    });
    if (attributes.actions.length) {
      await context.actionsAuthorization.ensureAuthorized({
        operation: 'execute'
      });
    }
  } 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.MUTE_ALERT,
      savedObject: {
        type: 'alert',
        id: alertId
      },
      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.MUTE_ALERT,
    outcome: 'unknown',
    savedObject: {
      type: 'alert',
      id: alertId
    }
  }));
  context.ruleTypeRegistry.ensureRuleTypeEnabled(attributes.alertTypeId);
  const mutedInstanceIds = attributes.mutedInstanceIds || [];
  if (!attributes.muteAll && !mutedInstanceIds.includes(alertInstanceId)) {
    mutedInstanceIds.push(alertInstanceId);
    await (0, _update_rule_so.updateRuleSo)({
      savedObjectsClient: context.unsecuredSavedObjectsClient,
      savedObjectsUpdateOptions: {
        version
      },
      id: alertId,
      updateRuleAttributes: (0, _lib.updateMeta)(context, {
        mutedInstanceIds,
        updatedBy: await context.getUserName(),
        updatedAt: new Date().toISOString()
      })
    });
  }
}