"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.deleteRule = deleteRule;
var _ruleDataUtils = require("@kbn/rule-data-utils");
var _authorization = require("../../authorization");
var _retry_if_conflicts = require("../../lib/retry_if_conflicts");
var _bulk_mark_api_keys_for_invalidation = require("../../invalidate_pending_api_keys/bulk_mark_api_keys_for_invalidation");
var _audit_events = require("../common/audit_events");
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 deleteRule(context, {
  id
}) {
  return await (0, _retry_if_conflicts.retryIfConflicts)(context.logger, `rulesClient.delete('${id}')`, async () => await deleteWithOCC(context, {
    id
  }));
}
async function deleteWithOCC(context, {
  id
}) {
  var _context$auditLogger2;
  let taskIdToRemove;
  let apiKeyToInvalidate = null;
  let apiKeyCreatedByUser = false;
  let attributes;
  try {
    const decryptedAlert = await context.encryptedSavedObjectsClient.getDecryptedAsInternalUser('alert', id, {
      namespace: context.namespace
    });
    apiKeyToInvalidate = decryptedAlert.attributes.apiKey;
    apiKeyCreatedByUser = decryptedAlert.attributes.apiKeyCreatedByUser;
    taskIdToRemove = decryptedAlert.attributes.scheduledTaskId;
    attributes = decryptedAlert.attributes;
  } catch (e) {
    // We'll skip invalidating the API key since we failed to load the decrypted saved object
    context.logger.error(`delete(): Failed to load API key to invalidate on alert ${id}: ${e.message}`);
    // Still attempt to load the scheduledTaskId using SOC
    const alert = await context.unsecuredSavedObjectsClient.get('alert', id);
    taskIdToRemove = alert.attributes.scheduledTaskId;
    attributes = alert.attributes;
  }
  try {
    await context.authorization.ensureAuthorized({
      ruleTypeId: attributes.alertTypeId,
      consumer: attributes.consumer,
      operation: _authorization.WriteOperations.Delete,
      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.DELETE,
      savedObject: {
        type: 'alert',
        id
      },
      error
    }));
    throw error;
  }
  await (0, _lib.untrackRuleAlerts)(context, id, attributes);

  // migrate legacy actions only for SIEM rules
  if (attributes.consumer === _ruleDataUtils.AlertConsumers.SIEM) {
    await (0, _lib.migrateLegacyActions)(context, {
      ruleId: id,
      attributes,
      skipActionsValidation: true
    });
  }
  (_context$auditLogger2 = context.auditLogger) === null || _context$auditLogger2 === void 0 ? void 0 : _context$auditLogger2.log((0, _audit_events.ruleAuditEvent)({
    action: _audit_events.RuleAuditAction.DELETE,
    outcome: 'unknown',
    savedObject: {
      type: 'alert',
      id
    }
  }));
  const removeResult = await context.unsecuredSavedObjectsClient.delete('alert', id);
  await Promise.all([taskIdToRemove ? context.taskManager.removeIfExists(taskIdToRemove) : null, apiKeyToInvalidate && !apiKeyCreatedByUser ? (0, _bulk_mark_api_keys_for_invalidation.bulkMarkApiKeysForInvalidation)({
    apiKeys: [apiKeyToInvalidate]
  }, context.logger, context.unsecuredSavedObjectsClient) : null]);
  return removeResult;
}