"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.performDeleteByNamespace = void 0;
var esKuery = _interopRequireWildcard(require("@kbn/es-query"));
var _coreElasticsearchServerInternal = require("@kbn/core-elasticsearch-server-internal");
var _coreSavedObjectsServer = require("@kbn/core-saved-objects-server");
var _coreSavedObjectsBaseServerInternal = require("@kbn/core-saved-objects-base-server-internal");
var _search = require("../search");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
 * 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 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

const performDeleteByNamespace = async ({
  namespace,
  options
}, {
  registry,
  helpers,
  client,
  mappings,
  extensions = {}
}) => {
  const {
    common: commonHelper
  } = helpers;
  // This is not exposed on the SOC; authorization and audit logging is handled by the Spaces plugin
  if (!namespace || typeof namespace !== 'string' || namespace === '*') {
    throw new TypeError(`namespace is required, and must be a string that is not equal to '*'`);
  }
  const allTypes = Object.keys((0, _coreSavedObjectsBaseServerInternal.getRootPropertiesObjects)(mappings));
  const typesToUpdate = [...allTypes.filter(type => !registry.isNamespaceAgnostic(type)), _coreSavedObjectsBaseServerInternal.LEGACY_URL_ALIAS_TYPE];

  // Construct kueryNode to filter legacy URL aliases (these space-agnostic objects do not use root-level "namespace/s" fields)
  const {
    buildNode
  } = esKuery.nodeTypes.function;
  const match1 = buildNode('is', `${_coreSavedObjectsBaseServerInternal.LEGACY_URL_ALIAS_TYPE}.targetNamespace`, namespace);
  const match2 = buildNode('not', buildNode('is', 'type', _coreSavedObjectsBaseServerInternal.LEGACY_URL_ALIAS_TYPE));
  const kueryNode = buildNode('or', [match1, match2]);
  const {
    body,
    statusCode,
    headers
  } = await client.updateByQuery({
    index: commonHelper.getIndicesForTypes(typesToUpdate),
    refresh: options.refresh,
    body: {
      script: {
        source: `
              if (!ctx._source.containsKey('namespaces')) {
                ctx.op = "delete";
              } else {
                ctx._source['namespaces'].removeAll(Collections.singleton(params['namespace']));
                if (ctx._source['namespaces'].empty) {
                  ctx.op = "delete";
                }
              }
            `,
        lang: 'painless',
        params: {
          namespace
        }
      },
      conflicts: 'proceed',
      ...(0, _search.getSearchDsl)(mappings, registry, {
        namespaces: [namespace],
        type: typesToUpdate,
        kueryNode
      })
    }
  }, {
    ignore: [404],
    meta: true
  });
  // throw if we can't verify a 404 response is from Elasticsearch
  if ((0, _coreElasticsearchServerInternal.isNotFoundFromUnsupportedServer)({
    statusCode,
    headers
  })) {
    throw _coreSavedObjectsServer.SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError();
  }
  return body;
};
exports.performDeleteByNamespace = performDeleteByNamespace;