"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.updateAgentHandler = exports.putAgentsReassignHandlerDeprecated = exports.postRetrieveAgentsByActionsHandler = exports.postBulkAgentsReassignHandler = exports.postAgentsReassignHandler = exports.getAvailableVersionsHandler = exports.getAgentsHandler = exports.getAgentUploadsHandler = exports.getAgentUploadFileHandler = exports.getAgentTagsHandler = exports.getAgentStatusForAgentPolicyHandler = exports.getAgentHandler = exports.getAgentDataHandler = exports.getActionStatusHandler = exports.deleteAgentHandler = exports.bulkUpdateAgentTagsHandler = void 0;
var _lodash = require("lodash");
var _server = require("@kbn/core/server");
var _errors = require("../../errors");
var AgentService = _interopRequireWildcard(require("../../services/agents"));
var _agent_metrics = require("../../services/agents/agent_metrics");
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; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const getAgentHandler = async (context, request, response) => {
  const coreContext = await context.core;
  const esClient = coreContext.elasticsearch.client.asInternalUser;
  const esClientCurrentUser = coreContext.elasticsearch.client.asCurrentUser;
  const soClient = coreContext.savedObjects.client;
  try {
    let agent = await AgentService.getAgentById(esClient, soClient, request.params.agentId);
    if (request.query.withMetrics) {
      agent = (await (0, _agent_metrics.fetchAndAssignAgentMetrics)(esClientCurrentUser, [agent]))[0];
    }
    const body = {
      item: agent
    };
    return response.ok({
      body
    });
  } catch (error) {
    if (_server.SavedObjectsErrorHelpers.isNotFoundError(error)) {
      return response.notFound({
        body: {
          message: `Agent ${request.params.agentId} not found`
        }
      });
    }
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.getAgentHandler = getAgentHandler;
const deleteAgentHandler = async (context, request, response) => {
  const coreContext = await context.core;
  const esClient = coreContext.elasticsearch.client.asInternalUser;
  try {
    await AgentService.deleteAgent(esClient, request.params.agentId);
    const body = {
      action: 'deleted'
    };
    return response.ok({
      body
    });
  } catch (error) {
    if (error.isBoom) {
      return response.customError({
        statusCode: error.output.statusCode,
        body: {
          message: `Agent ${request.params.agentId} not found`
        }
      });
    }
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.deleteAgentHandler = deleteAgentHandler;
const updateAgentHandler = async (context, request, response) => {
  const coreContext = await context.core;
  const esClient = coreContext.elasticsearch.client.asInternalUser;
  const soClient = coreContext.savedObjects.client;
  const partialAgent = {};
  if (request.body.user_provided_metadata) {
    partialAgent.user_provided_metadata = request.body.user_provided_metadata;
  }
  if (request.body.tags) {
    partialAgent.tags = (0, _lodash.uniq)(request.body.tags);
  }
  try {
    await AgentService.updateAgent(esClient, request.params.agentId, partialAgent);
    const body = {
      item: await AgentService.getAgentById(esClient, soClient, request.params.agentId)
    };
    return response.ok({
      body
    });
  } catch (error) {
    if (error.isBoom && error.output.statusCode === 404) {
      return response.notFound({
        body: {
          message: `Agent ${request.params.agentId} not found`
        }
      });
    }
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.updateAgentHandler = updateAgentHandler;
const bulkUpdateAgentTagsHandler = async (context, request, response) => {
  const coreContext = await context.core;
  const esClient = coreContext.elasticsearch.client.asInternalUser;
  const soClient = coreContext.savedObjects.client;
  const agentOptions = Array.isArray(request.body.agents) ? {
    agentIds: request.body.agents
  } : {
    kuery: request.body.agents
  };
  try {
    var _request$body$tagsToA, _request$body$tagsToR;
    const results = await AgentService.updateAgentTags(soClient, esClient, {
      ...agentOptions,
      batchSize: request.body.batchSize
    }, (_request$body$tagsToA = request.body.tagsToAdd) !== null && _request$body$tagsToA !== void 0 ? _request$body$tagsToA : [], (_request$body$tagsToR = request.body.tagsToRemove) !== null && _request$body$tagsToR !== void 0 ? _request$body$tagsToR : []);
    return response.ok({
      body: {
        actionId: results.actionId
      }
    });
  } catch (error) {
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.bulkUpdateAgentTagsHandler = bulkUpdateAgentTagsHandler;
const getAgentsHandler = async (context, request, response) => {
  const coreContext = await context.core;
  const esClient = coreContext.elasticsearch.client.asInternalUser;
  const esClientCurrentUser = coreContext.elasticsearch.client.asCurrentUser;
  const soClient = coreContext.savedObjects.client;
  try {
    const agentRes = await AgentService.getAgentsByKuery(esClient, soClient, {
      page: request.query.page,
      perPage: request.query.perPage,
      showInactive: request.query.showInactive,
      showUpgradeable: request.query.showUpgradeable,
      kuery: request.query.kuery,
      sortField: request.query.sortField,
      sortOrder: request.query.sortOrder,
      getStatusSummary: request.query.getStatusSummary
    });
    const {
      total,
      page,
      perPage,
      statusSummary
    } = agentRes;
    let {
      agents
    } = agentRes;

    // Assign metrics
    if (request.query.withMetrics) {
      agents = await (0, _agent_metrics.fetchAndAssignAgentMetrics)(esClientCurrentUser, agents);
    }
    const body = {
      list: agents,
      // deprecated
      items: agents,
      total,
      page,
      perPage,
      ...(statusSummary ? {
        statusSummary
      } : {})
    };
    return response.ok({
      body
    });
  } catch (error) {
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.getAgentsHandler = getAgentsHandler;
const getAgentTagsHandler = async (context, request, response) => {
  const coreContext = await context.core;
  const esClient = coreContext.elasticsearch.client.asInternalUser;
  const soClient = coreContext.savedObjects.client;
  try {
    const tags = await AgentService.getAgentTags(soClient, esClient, {
      showInactive: request.query.showInactive,
      kuery: request.query.kuery
    });
    const body = {
      items: tags
    };
    return response.ok({
      body
    });
  } catch (error) {
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.getAgentTagsHandler = getAgentTagsHandler;
const putAgentsReassignHandlerDeprecated = async (context, request, response) => {
  const coreContext = await context.core;
  const soClient = coreContext.savedObjects.client;
  const esClient = coreContext.elasticsearch.client.asInternalUser;
  try {
    await AgentService.reassignAgent(soClient, esClient, request.params.agentId, request.body.policy_id);
    const body = {};
    return response.ok({
      body
    });
  } catch (error) {
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.putAgentsReassignHandlerDeprecated = putAgentsReassignHandlerDeprecated;
const postAgentsReassignHandler = async (context, request, response) => {
  const coreContext = await context.core;
  const soClient = coreContext.savedObjects.client;
  const esClient = coreContext.elasticsearch.client.asInternalUser;
  try {
    await AgentService.reassignAgent(soClient, esClient, request.params.agentId, request.body.policy_id);
    const body = {};
    return response.ok({
      body
    });
  } catch (error) {
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.postAgentsReassignHandler = postAgentsReassignHandler;
const postBulkAgentsReassignHandler = async (context, request, response) => {
  const coreContext = await context.core;
  const soClient = coreContext.savedObjects.client;
  const esClient = coreContext.elasticsearch.client.asInternalUser;
  const agentOptions = Array.isArray(request.body.agents) ? {
    agentIds: request.body.agents
  } : {
    kuery: request.body.agents
  };
  try {
    const results = await AgentService.reassignAgents(soClient, esClient, {
      ...agentOptions,
      batchSize: request.body.batchSize
    }, request.body.policy_id);
    return response.ok({
      body: {
        actionId: results.actionId
      }
    });
  } catch (error) {
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.postBulkAgentsReassignHandler = postBulkAgentsReassignHandler;
const getAgentStatusForAgentPolicyHandler = async (context, request, response) => {
  const coreContext = await context.core;
  const esClient = coreContext.elasticsearch.client.asInternalUser;
  const soClient = coreContext.savedObjects.client;
  try {
    const results = await AgentService.getAgentStatusForAgentPolicy(esClient, soClient, request.query.policyId, request.query.kuery);
    const body = {
      results
    };
    return response.ok({
      body
    });
  } catch (error) {
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.getAgentStatusForAgentPolicyHandler = getAgentStatusForAgentPolicyHandler;
const getAgentDataHandler = async (context, request, response) => {
  const coreContext = await context.core;
  const esClient = coreContext.elasticsearch.client.asCurrentUser;
  try {
    const returnDataPreview = request.query.previewData;
    const agentIds = isStringArray(request.query.agentsIds) ? request.query.agentsIds : [request.query.agentsIds];
    const {
      items,
      dataPreview
    } = await AgentService.getIncomingDataByAgentsId(esClient, agentIds, returnDataPreview);
    const body = {
      items,
      dataPreview
    };
    return response.ok({
      body
    });
  } catch (error) {
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.getAgentDataHandler = getAgentDataHandler;
function isStringArray(arr) {
  return Array.isArray(arr) && arr.every(p => typeof p === 'string');
}
const getAvailableVersionsHandler = async (context, request, response) => {
  try {
    const availableVersions = await AgentService.getAvailableVersions();
    const body = {
      items: availableVersions
    };
    return response.ok({
      body
    });
  } catch (error) {
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.getAvailableVersionsHandler = getAvailableVersionsHandler;
const getActionStatusHandler = async (context, request, response) => {
  const coreContext = await context.core;
  const esClient = coreContext.elasticsearch.client.asInternalUser;
  try {
    const actionStatuses = await AgentService.getActionStatuses(esClient, request.query);
    const body = {
      items: actionStatuses
    };
    return response.ok({
      body
    });
  } catch (error) {
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.getActionStatusHandler = getActionStatusHandler;
const postRetrieveAgentsByActionsHandler = async (context, request, response) => {
  const coreContext = await context.core;
  const esClient = coreContext.elasticsearch.client.asInternalUser;
  try {
    const agents = await AgentService.getAgentsByActionsIds(esClient, request.body.actionIds);
    const body = {
      items: agents
    };
    return response.ok({
      body
    });
  } catch (error) {
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.postRetrieveAgentsByActionsHandler = postRetrieveAgentsByActionsHandler;
const getAgentUploadsHandler = async (context, request, response) => {
  const coreContext = await context.core;
  const esClient = coreContext.elasticsearch.client.asInternalUser;
  try {
    const body = {
      items: await AgentService.getAgentUploads(esClient, request.params.agentId)
    };
    return response.ok({
      body
    });
  } catch (error) {
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.getAgentUploadsHandler = getAgentUploadsHandler;
const getAgentUploadFileHandler = async (context, request, response) => {
  const coreContext = await context.core;
  const esClient = coreContext.elasticsearch.client.asInternalUser;
  try {
    const resp = await AgentService.getAgentUploadFile(esClient, request.params.fileId, request.params.fileName);
    return response.ok(resp);
  } catch (error) {
    return (0, _errors.defaultFleetErrorHandler)({
      error,
      response
    });
  }
};
exports.getAgentUploadFileHandler = getAgentUploadFileHandler;