"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.updateCases = exports.resolveCase = exports.pushCase = exports.postComment = exports.postCase = exports.patchComment = exports.patchCase = exports.getTags = exports.getSingleCaseMetrics = exports.getReporters = exports.getFeatureIds = exports.getCategories = exports.getCases = exports.getCaseUsers = exports.getCaseUserActionsStats = exports.getCaseConnectors = exports.getCase = exports.getActionLicense = exports.findCaseUserActions = exports.deleteFileAttachments = exports.deleteComment = exports.deleteCases = exports.createAttachments = void 0;
var _constants = require("@kbn/rule-registry-plugin/common/constants");
var _domain = require("../../common/types/domain");
var _types = require("../../common/ui/types");
var _api = require("../../common/api");
var _constants2 = require("../../common/constants");
var _connectors_api = require("../../common/utils/connectors_api");
var _kibana = require("../common/lib/kibana");
var _utils = require("../api/utils");
var _utils2 = require("./utils");
var _decoders = require("../api/decoders");
/*
 * 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 getCase = async (caseId, includeComments = true, signal) => {
  const response = await _kibana.KibanaServices.get().http.fetch((0, _api.getCaseDetailsUrl)(caseId), {
    method: 'GET',
    query: {
      includeComments
    },
    signal
  });
  return (0, _utils.convertCaseToCamelCase)((0, _utils2.decodeCaseResponse)(response));
};
exports.getCase = getCase;
const resolveCase = async ({
  caseId,
  includeComments = true,
  signal
}) => {
  const response = await _kibana.KibanaServices.get().http.fetch(`${(0, _api.getCaseDetailsUrl)(caseId)}/resolve`, {
    method: 'GET',
    query: {
      includeComments
    },
    signal
  });
  return (0, _utils.convertCaseResolveToCamelCase)((0, _utils2.decodeCaseResolveResponse)(response));
};
exports.resolveCase = resolveCase;
const getTags = async ({
  owner,
  signal
}) => {
  const response = await _kibana.KibanaServices.get().http.fetch(_constants2.CASE_TAGS_URL, {
    method: 'GET',
    signal,
    query: {
      ...(owner.length > 0 ? {
        owner
      } : {})
    }
  });
  return response !== null && response !== void 0 ? response : [];
};
exports.getTags = getTags;
const getCategories = async ({
  owner,
  signal
}) => {
  const response = await _kibana.KibanaServices.get().http.fetch(_constants2.INTERNAL_GET_CASE_CATEGORIES_URL, {
    method: 'GET',
    signal,
    query: {
      ...(owner.length > 0 ? {
        owner
      } : {})
    }
  });
  return response !== null && response !== void 0 ? response : [];
};
exports.getCategories = getCategories;
const getReporters = async (signal, owner) => {
  const response = await _kibana.KibanaServices.get().http.fetch(_constants2.CASE_REPORTERS_URL, {
    method: 'GET',
    signal,
    query: {
      ...(owner.length > 0 ? {
        owner
      } : {})
    }
  });
  return response !== null && response !== void 0 ? response : [];
};
exports.getReporters = getReporters;
const getSingleCaseMetrics = async (caseId, features, signal) => {
  const response = await _kibana.KibanaServices.get().http.fetch((0, _api.getCaseDetailsMetricsUrl)(caseId), {
    method: 'GET',
    signal,
    query: {
      features: JSON.stringify(features)
    }
  });
  return (0, _utils.convertToCamelCase)((0, _utils2.decodeSingleCaseMetricsResponse)(response));
};
exports.getSingleCaseMetrics = getSingleCaseMetrics;
const findCaseUserActions = async (caseId, params, signal) => {
  const query = {
    types: params.type !== 'all' ? [params.type] : [],
    sortOrder: params.sortOrder,
    page: params.page,
    perPage: params.perPage
  };
  const response = await _kibana.KibanaServices.get().http.fetch((0, _api.getCaseFindUserActionsUrl)(caseId), {
    method: 'GET',
    query,
    signal
  });
  return {
    ...response,
    userActions: (0, _utils.convertUserActionsToCamelCase)((0, _utils2.decodeCaseUserActionsResponse)(response.userActions))
  };
};
exports.findCaseUserActions = findCaseUserActions;
const getCaseUserActionsStats = async (caseId, signal) => {
  const response = await _kibana.KibanaServices.get().http.fetch((0, _api.getCaseUserActionStatsUrl)(caseId), {
    method: 'GET',
    signal
  });
  return (0, _utils.convertToCamelCase)((0, _utils2.decodeCaseUserActionStatsResponse)(response));
};
exports.getCaseUserActionsStats = getCaseUserActionsStats;
const getCases = async ({
  filterOptions = {
    search: '',
    searchFields: [],
    severity: _types.SeverityAll,
    assignees: [],
    reporters: [],
    status: _types.StatusAll,
    tags: [],
    owner: [],
    category: []
  },
  queryParams = {
    page: 1,
    perPage: 20,
    sortField: _types.SortFieldCase.createdAt,
    sortOrder: 'desc'
  },
  signal
}) => {
  const query = {
    ...(filterOptions.status !== _types.StatusAll ? {
      status: filterOptions.status
    } : {}),
    ...(filterOptions.severity !== _types.SeverityAll ? {
      severity: filterOptions.severity
    } : {}),
    ...(0, _utils2.constructAssigneesFilter)(filterOptions.assignees),
    ...(0, _utils2.constructReportersFilter)(filterOptions.reporters),
    ...(filterOptions.tags.length > 0 ? {
      tags: filterOptions.tags
    } : {}),
    ...(filterOptions.search.length > 0 ? {
      search: filterOptions.search
    } : {}),
    ...(filterOptions.searchFields.length > 0 ? {
      searchFields: filterOptions.searchFields
    } : {}),
    ...(filterOptions.owner.length > 0 ? {
      owner: filterOptions.owner
    } : {}),
    ...(filterOptions.category.length > 0 ? {
      category: filterOptions.category
    } : {}),
    ...queryParams
  };
  const response = await _kibana.KibanaServices.get().http.fetch(`${_constants2.CASES_URL}/_find`, {
    method: 'GET',
    query,
    signal
  });
  return (0, _utils.convertAllCasesToCamel)((0, _decoders.decodeCasesFindResponse)(response));
};
exports.getCases = getCases;
const postCase = async ({
  newCase,
  signal
}) => {
  const theCase = {
    ...newCase,
    ...(newCase.category != null ? {
      category: newCase.category
    } : {
      category: null
    })
  };
  const response = await _kibana.KibanaServices.get().http.fetch(_constants2.CASES_URL, {
    method: 'POST',
    body: JSON.stringify(theCase),
    signal
  });
  return (0, _utils.convertCaseToCamelCase)((0, _utils2.decodeCaseResponse)(response));
};
exports.postCase = postCase;
const patchCase = async ({
  caseId,
  updatedCase,
  version,
  signal
}) => {
  const response = await _kibana.KibanaServices.get().http.fetch(_constants2.CASES_URL, {
    method: 'PATCH',
    body: JSON.stringify({
      cases: [{
        ...updatedCase,
        id: caseId,
        version
      }]
    }),
    signal
  });
  return (0, _utils.convertCasesToCamelCase)((0, _utils2.decodeCasesResponse)(response));
};
exports.patchCase = patchCase;
const updateCases = async ({
  cases,
  signal
}) => {
  if (cases.length === 0) {
    return [];
  }
  const response = await _kibana.KibanaServices.get().http.fetch(_constants2.CASES_URL, {
    method: 'PATCH',
    body: JSON.stringify({
      cases
    }),
    signal
  });
  return (0, _utils.convertCasesToCamelCase)((0, _utils2.decodeCasesResponse)(response));
};
exports.updateCases = updateCases;
const postComment = async (newComment, caseId, signal) => {
  const response = await _kibana.KibanaServices.get().http.fetch(`${_constants2.CASES_URL}/${caseId}/comments`, {
    method: 'POST',
    body: JSON.stringify(newComment),
    signal
  });
  return (0, _utils.convertCaseToCamelCase)((0, _utils2.decodeCaseResponse)(response));
};
exports.postComment = postComment;
const patchComment = async ({
  caseId,
  commentId,
  commentUpdate,
  version,
  owner,
  signal
}) => {
  const response = await _kibana.KibanaServices.get().http.fetch((0, _api.getCaseCommentsUrl)(caseId), {
    method: 'PATCH',
    body: JSON.stringify({
      comment: commentUpdate,
      type: _domain.AttachmentType.user,
      id: commentId,
      version,
      owner
    }),
    signal
  });
  return (0, _utils.convertCaseToCamelCase)((0, _utils2.decodeCaseResponse)(response));
};
exports.patchComment = patchComment;
const deleteComment = async ({
  caseId,
  commentId,
  signal
}) => {
  await _kibana.KibanaServices.get().http.fetch((0, _api.getCaseCommentDeleteUrl)(caseId, commentId), {
    method: 'DELETE',
    signal
  });
};
exports.deleteComment = deleteComment;
const deleteCases = async ({
  caseIds,
  signal
}) => {
  const response = await _kibana.KibanaServices.get().http.fetch(_constants2.CASES_URL, {
    method: 'DELETE',
    query: {
      ids: JSON.stringify(caseIds)
    },
    signal
  });
  return response;
};
exports.deleteCases = deleteCases;
const pushCase = async ({
  caseId,
  connectorId,
  signal
}) => {
  const response = await _kibana.KibanaServices.get().http.fetch((0, _api.getCasePushUrl)(caseId, connectorId), {
    method: 'POST',
    body: JSON.stringify({}),
    signal
  });
  return (0, _utils.convertCaseToCamelCase)((0, _utils2.decodeCaseResponse)(response));
};
exports.pushCase = pushCase;
const getActionLicense = async signal => {
  const response = await _kibana.KibanaServices.get().http.fetch((0, _connectors_api.getAllConnectorTypesUrl)(), {
    method: 'GET',
    signal
  });
  return (0, _utils.convertArrayToCamelCase)(response);
};
exports.getActionLicense = getActionLicense;
const createAttachments = async ({
  attachments,
  caseId,
  signal
}) => {
  const response = await _kibana.KibanaServices.get().http.fetch(_constants2.INTERNAL_BULK_CREATE_ATTACHMENTS_URL.replace('{case_id}', caseId), {
    method: 'POST',
    body: JSON.stringify(attachments),
    signal
  });
  return (0, _utils.convertCaseToCamelCase)((0, _utils2.decodeCaseResponse)(response));
};
exports.createAttachments = createAttachments;
const deleteFileAttachments = async ({
  caseId,
  fileIds,
  signal
}) => {
  await _kibana.KibanaServices.get().http.fetch((0, _api.getCasesDeleteFileAttachmentsUrl)(caseId), {
    method: 'POST',
    body: JSON.stringify({
      ids: fileIds
    }),
    signal
  });
};
exports.deleteFileAttachments = deleteFileAttachments;
const getFeatureIds = async ({
  query,
  signal
}) => {
  return _kibana.KibanaServices.get().http.fetch(`${_constants.BASE_RAC_ALERTS_API_PATH}/_feature_ids`, {
    signal,
    query
  });
};
exports.getFeatureIds = getFeatureIds;
const getCaseConnectors = async (caseId, signal) => {
  const res = await _kibana.KibanaServices.get().http.fetch((0, _api.getCaseConnectorsUrl)(caseId), {
    method: 'GET',
    signal
  });
  return Object.keys(res).reduce((acc, connectorId) => {
    acc[connectorId] = {
      ...(0, _utils.convertToCamelCase)(res[connectorId])
    };
    return acc;
  }, {});
};
exports.getCaseConnectors = getCaseConnectors;
const getCaseUsers = async ({
  caseId,
  signal
}) => {
  return _kibana.KibanaServices.get().http.fetch((0, _api.getCaseUsersUrl)(caseId), {
    method: 'GET',
    signal
  });
};
exports.getCaseUsers = getCaseUsers;