"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.muteAll = muteAll;
var _authorization = require("../../authorization");
var _retry_if_conflicts = require("../../lib/retry_if_conflicts");
var _saved_objects = require("../../saved_objects");
var _audit_events = require("../common/audit_events");
var _lib = require("../lib");
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.
 */

async function muteAll(context, {
  id
}) {
  return await (0, _retry_if_conflicts.retryIfConflicts)(context.logger, `rulesClient.muteAll('${id}')`, async () => await muteAllWithOCC(context, {
    id
  }));
}
async function muteAllWithOCC(context, {
  id
}) {
  var _context$auditLogger2;
  const {
    attributes,
    version
  } = await context.unsecuredSavedObjectsClient.get('alert', id);
  try {
    await context.authorization.ensureAuthorized({
      ruleTypeId: attributes.alertTypeId,
      consumer: attributes.consumer,
      operation: _authorization.WriteOperations.MuteAll,
      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,
      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.MUTE,
    outcome: 'unknown',
    savedObject: {
      type: 'alert',
      id
    }
  }));
  context.ruleTypeRegistry.ensureRuleTypeEnabled(attributes.alertTypeId);
  const updateAttributes = (0, _lib.updateMeta)(context, {
    muteAll: true,
    mutedInstanceIds: [],
    snoozeSchedule: (0, _common.clearUnscheduledSnoozeAttributes)(attributes),
    updatedBy: await context.getUserName(),
    updatedAt: new Date().toISOString()
  });
  const updateOptions = {
    version
  };
  await (0, _saved_objects.partiallyUpdateAlert)(context.unsecuredSavedObjectsClient, id, updateAttributes, updateOptions);
}