"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.updateApiKey = updateApiKey;
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 updateApiKey(context, {
  id
}) {
  return await (0, _retry_if_conflicts.retryIfConflicts)(context.logger, `rulesClient.updateApiKey('${id}')`, async () => await updateApiKeyWithOCC(context, {
    id
  }));
}
async function updateApiKeyWithOCC(context, {
  id
}) {
  var _context$auditLogger2;
  let oldApiKeyToInvalidate = null;
  let oldApiKeyCreatedByUser = false;
  let attributes;
  let version;
  try {
    const decryptedAlert = await context.encryptedSavedObjectsClient.getDecryptedAsInternalUser('alert', id, {
      namespace: context.namespace
    });
    oldApiKeyToInvalidate = decryptedAlert.attributes.apiKey;
    oldApiKeyCreatedByUser = decryptedAlert.attributes.apiKeyCreatedByUser;
    attributes = decryptedAlert.attributes;
    version = decryptedAlert.version;
  } catch (e) {
    // We'll skip invalidating the API key since we failed to load the decrypted saved object
    context.logger.error(`updateApiKey(): Failed to load API key to invalidate on alert ${id}: ${e.message}`);
    // Still attempt to load the attributes and version using SOC
    const alert = await context.unsecuredSavedObjectsClient.get('alert', id);
    attributes = alert.attributes;
    version = alert.version;
  }
  try {
    await context.authorization.ensureAuthorized({
      ruleTypeId: attributes.alertTypeId,
      consumer: attributes.consumer,
      operation: _authorization.WriteOperations.UpdateApiKey,
      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.UPDATE_API_KEY,
      savedObject: {
        type: 'alert',
        id
      },
      error
    }));
    throw error;
  }
  const username = await context.getUserName();
  const apiKeyAttributes = await (0, _lib.createNewAPIKeySet)(context, {
    id: attributes.alertTypeId,
    ruleName: attributes.name,
    username,
    shouldUpdateApiKey: true,
    errorMessage: 'Error updating API key for rule: could not create API key'
  });
  const updateAttributes = (0, _lib.updateMeta)(context, {
    ...attributes,
    ...apiKeyAttributes,
    updatedAt: new Date().toISOString(),
    updatedBy: username
  });
  (_context$auditLogger2 = context.auditLogger) === null || _context$auditLogger2 === void 0 ? void 0 : _context$auditLogger2.log((0, _audit_events.ruleAuditEvent)({
    action: _audit_events.RuleAuditAction.UPDATE_API_KEY,
    outcome: 'unknown',
    savedObject: {
      type: 'alert',
      id
    }
  }));
  context.ruleTypeRegistry.ensureRuleTypeEnabled(attributes.alertTypeId);
  try {
    await context.unsecuredSavedObjectsClient.update('alert', id, updateAttributes, {
      version
    });
  } catch (e) {
    // Avoid unused API key
    await (0, _bulk_mark_api_keys_for_invalidation.bulkMarkApiKeysForInvalidation)({
      apiKeys: updateAttributes.apiKey && !updateAttributes.apiKeyCreatedByUser ? [updateAttributes.apiKey] : []
    }, context.logger, context.unsecuredSavedObjectsClient);
    throw e;
  }
  if (oldApiKeyToInvalidate && !oldApiKeyCreatedByUser) {
    await (0, _bulk_mark_api_keys_for_invalidation.bulkMarkApiKeysForInvalidation)({
      apiKeys: [oldApiKeyToInvalidate]
    }, context.logger, context.unsecuredSavedObjectsClient);
  }
}