"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getKuery = void 0;
var _services = require("../../../../services");
var _constants = require("../../../../constants");
/*
 * 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 getKuery = ({
  search,
  selectedAgentPolicies,
  selectedTags,
  selectedStatus,
  selectedAgentIds
}) => {
  let kueryBuilder = '';
  if (search) {
    kueryBuilder = search.trim();
  }
  if (selectedAgentPolicies !== null && selectedAgentPolicies !== void 0 && selectedAgentPolicies.length) {
    if (kueryBuilder) {
      kueryBuilder = `(${kueryBuilder}) and`;
    }
    kueryBuilder = `${kueryBuilder} ${_constants.AGENTS_PREFIX}.policy_id : (${selectedAgentPolicies.map(agentPolicy => `"${agentPolicy}"`).join(' or ')})`;
  }
  if (selectedTags !== null && selectedTags !== void 0 && selectedTags.length) {
    if (kueryBuilder) {
      kueryBuilder = `(${kueryBuilder}) and`;
    }
    kueryBuilder = `${kueryBuilder} ${_constants.AGENTS_PREFIX}.tags : (${selectedTags.map(tag => `"${tag}"`).join(' or ')})`;
  }
  if (selectedAgentIds !== null && selectedAgentIds !== void 0 && selectedAgentIds.length) {
    if (kueryBuilder) {
      kueryBuilder = `(${kueryBuilder}) and`;
    }
    kueryBuilder = `${kueryBuilder} ${_constants.AGENTS_PREFIX}.agent.id : (${selectedAgentIds.map(id => `"${id}"`).join(' or ')})`;
  }
  if (selectedStatus !== null && selectedStatus !== void 0 && selectedStatus.length) {
    const kueryStatus = selectedStatus.map(status => {
      switch (status) {
        case 'healthy':
          return _services.AgentStatusKueryHelper.buildKueryForOnlineAgents();
        case 'unhealthy':
          return _services.AgentStatusKueryHelper.buildKueryForErrorAgents();
        case 'offline':
          return _services.AgentStatusKueryHelper.buildKueryForOfflineAgents();
        case 'updating':
          return _services.AgentStatusKueryHelper.buildKueryForUpdatingAgents();
        case 'inactive':
          return _services.AgentStatusKueryHelper.buildKueryForInactiveAgents();
        case 'unenrolled':
          return _services.AgentStatusKueryHelper.buildKueryForUnenrolledAgents();
      }
      return undefined;
    }).filter(statusKuery => statusKuery !== undefined).join(' or ');
    if (kueryBuilder) {
      kueryBuilder = `(${kueryBuilder}) and (${kueryStatus})`;
    } else {
      kueryBuilder = kueryStatus;
    }
  }
  return kueryBuilder.trim();
};
exports.getKuery = getKuery;