"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.registerCleanRoute = void 0;
var _configSchema = require("@kbn/config-schema");
var _utils = require("./utils");
/*
 * 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 registerCleanRoute = router => {
  router.post({
    path: `${_utils.KBN_CLIENT_API_PREFIX}/_clean`,
    options: {
      tags: ['access:ftrApis']
    },
    validate: {
      body: _configSchema.schema.object({
        types: _configSchema.schema.arrayOf(_configSchema.schema.string())
      })
    }
  }, (0, _utils.catchAndReturnBoomErrors)(async (ctx, req, res) => {
    const {
      types
    } = req.body;
    const {
      savedObjects
    } = await ctx.core;
    const hiddenTypes = (0, _utils.listHiddenTypes)(savedObjects.typeRegistry);
    const soClient = savedObjects.getClient({
      includedHiddenTypes: hiddenTypes
    });
    const finder = soClient.createPointInTimeFinder({
      type: types,
      perPage: 100
    });
    let deleted = 0;
    for await (const response of finder.find()) {
      const objects = response.saved_objects.map(({
        type,
        id
      }) => ({
        type,
        id
      }));
      const {
        statuses
      } = await soClient.bulkDelete(objects, {
        force: true
      });
      deleted += statuses.filter(status => status.success).length;
    }
    return res.ok({
      body: {
        deleted
      }
    });
  }));
};
exports.registerCleanRoute = registerCleanRoute;