"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.putFleetProxyHandler = exports.postFleetProxyHandler = exports.getFleetProxyHandler = exports.getAllFleetProxyHandler = exports.deleteFleetProxyHandler = void 0;
var _server = require("@kbn/core/server");
var _pMap = _interopRequireDefault(require("p-map"));
var _fleet_proxies = require("../../services/fleet_proxies");
var _errors = require("../../errors");
var _services = require("../../services");
/*
 * 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 bumpRelatedPolicies(soClient, esClient, fleetServerHosts, outputs, downloadSources) {
  if (fleetServerHosts.some(host => host.is_default) || outputs.some(output => output.is_default || output.is_default_monitoring)) {
    await _services.agentPolicyService.bumpAllAgentPolicies(soClient, esClient);
  } else {
    await (0, _pMap.default)(outputs, output => _services.agentPolicyService.bumpAllAgentPoliciesForOutput(soClient, esClient, output.id), {
      concurrency: 20
    });
    await (0, _pMap.default)(fleetServerHosts, fleetServerHost => _services.agentPolicyService.bumpAllAgentPoliciesForFleetServerHosts(soClient, esClient, fleetServerHost.id), {
      concurrency: 20
    });
    await (0, _pMap.default)(downloadSources, downloadSource => _services.agentPolicyService.bumpAllAgentPoliciesForDownloadSource(soClient, esClient, downloadSource.id), {
      concurrency: 20
    });
  }
}
function checkProxiesAvailable() {
  var _appContextService$ge, _appContextService$ge2;
  if ((_appContextService$ge = _services.appContextService.getConfig()) !== null && _appContextService$ge !== void 0 && (_appContextService$ge2 = _appContextService$ge.internal) !== null && _appContextService$ge2 !== void 0 && _appContextService$ge2.disableProxies) {
    throw new _errors.FleetProxyUnauthorizedError('Proxies write APIs are disabled');
  }
}
const postFleetProxyHandler = async (context, request, response) => {
  const coreContext = await context.core;
  const soClient = coreContext.savedObjects.client;
  try {
    checkProxiesAvailable();
    const {
      id,
      ...data
    } = request.body;
    const proxy = await (0, _fleet_proxies.createFleetProxy)(soClient, {
      ...data,
      is_preconfigured: false
    }, {
      id
    });
    const body = {
      item: proxy
    };
    return response.ok({
      body
    });
  } catch (error) {
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.postFleetProxyHandler = postFleetProxyHandler;
const putFleetProxyHandler = async (context, request, response) => {
  try {
    checkProxiesAvailable();
    const proxyId = request.params.itemId;
    const coreContext = await await context.core;
    const soClient = coreContext.savedObjects.client;
    const esClient = coreContext.elasticsearch.client.asInternalUser;
    const item = await (0, _fleet_proxies.updateFleetProxy)(soClient, proxyId, request.body);
    const body = {
      item
    };

    // Bump all the agent policy that use that proxy
    const {
      fleetServerHosts,
      outputs,
      downloadSources
    } = await (0, _fleet_proxies.getFleetProxyRelatedSavedObjects)(soClient, proxyId);
    await bumpRelatedPolicies(soClient, esClient, fleetServerHosts, outputs, downloadSources);
    return response.ok({
      body
    });
  } catch (error) {
    if (_server.SavedObjectsErrorHelpers.isNotFoundError(error)) {
      return response.notFound({
        body: {
          message: `Proxy ${request.params.itemId} not found`
        }
      });
    }
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.putFleetProxyHandler = putFleetProxyHandler;
const getAllFleetProxyHandler = async (context, request, response) => {
  const soClient = (await context.core).savedObjects.client;
  try {
    const res = await (0, _fleet_proxies.listFleetProxies)(soClient);
    const body = {
      items: res.items,
      page: res.page,
      perPage: res.perPage,
      total: res.total
    };
    return response.ok({
      body
    });
  } catch (error) {
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.getAllFleetProxyHandler = getAllFleetProxyHandler;
const deleteFleetProxyHandler = async (context, request, response) => {
  try {
    checkProxiesAvailable();
    const proxyId = request.params.itemId;
    const coreContext = await context.core;
    const soClient = coreContext.savedObjects.client;
    const esClient = coreContext.elasticsearch.client.asInternalUser;
    const {
      fleetServerHosts,
      outputs,
      downloadSources
    } = await (0, _fleet_proxies.getFleetProxyRelatedSavedObjects)(soClient, proxyId);
    await (0, _fleet_proxies.deleteFleetProxy)(soClient, esClient, request.params.itemId);
    await bumpRelatedPolicies(soClient, esClient, fleetServerHosts, outputs, downloadSources);
    const body = {
      id: request.params.itemId
    };
    return response.ok({
      body
    });
  } catch (error) {
    if (_server.SavedObjectsErrorHelpers.isNotFoundError(error)) {
      return response.notFound({
        body: {
          message: `Fleet proxy ${request.params.itemId} not found`
        }
      });
    }
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.deleteFleetProxyHandler = deleteFleetProxyHandler;
const getFleetProxyHandler = async (context, request, response) => {
  const soClient = (await context.core).savedObjects.client;
  try {
    const item = await (0, _fleet_proxies.getFleetProxy)(soClient, request.params.itemId);
    const body = {
      item
    };
    return response.ok({
      body
    });
  } catch (error) {
    if (_server.SavedObjectsErrorHelpers.isNotFoundError(error)) {
      return response.notFound({
        body: {
          message: `Fleet proxy ${request.params.itemId} not found`
        }
      });
    }
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.getFleetProxyHandler = getFleetProxyHandler;