"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useLatestFindings = exports.getFindingsQuery = void 0;
var _reactQuery = require("@tanstack/react-query");
var _ioTs = require("io-ts");
var _rxjs = require("rxjs");
var _discoverUtils = require("@kbn/discover-utils");
var _use_kibana = require("../../../common/hooks/use_kibana");
var _utils = require("../utils/utils");
var _constants = require("../../../../common/constants");
var _constants2 = require("../../../common/constants");
var _show_error_toast = require("../../../common/utils/show_error_toast");
/*
 * 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 getFindingsQuery = ({
  query,
  sort
}, pageParam) => ({
  index: _constants.CSP_LATEST_FINDINGS_DATA_VIEW,
  query,
  sort: getMultiFieldsSort(sort),
  size: _constants2.MAX_FINDINGS_TO_LOAD,
  aggs: (0, _utils.getFindingsCountAggQuery)(),
  ignore_unavailable: false,
  ...(pageParam ? {
    search_after: pageParam
  } : {})
});
exports.getFindingsQuery = getFindingsQuery;
const getMultiFieldsSort = sort => {
  return sort.map(([id, direction]) => {
    return {
      ...getSortField({
        field: id,
        direction
      })
    };
  });
};

/**
 * By default, ES will sort keyword fields in case-sensitive format, the
 * following fields are required to have a case-insensitive sorting.
 */
const fieldsRequiredSortingByPainlessScript = ['rule.section', 'resource.name', 'resource.sub_type'];

/**
 * Generates Painless sorting if the given field is matched or returns default sorting
 * This painless script will sort the field in case-insensitive manner
 */
const getSortField = ({
  field,
  direction
}) => {
  if (fieldsRequiredSortingByPainlessScript.includes(field)) {
    return {
      _script: {
        type: 'string',
        order: direction,
        script: {
          source: `doc["${field}"].value.toLowerCase()`,
          lang: 'painless'
        }
      }
    };
  }
  return {
    [field]: direction
  };
};
const useLatestFindings = options => {
  const {
    data,
    notifications: {
      toasts
    }
  } = (0, _use_kibana.useKibana)().services;
  return (0, _reactQuery.useInfiniteQuery)(['csp_findings', {
    params: options
  }], async ({
    pageParam
  }) => {
    const {
      rawResponse: {
        hits,
        aggregations
      }
    } = await (0, _rxjs.lastValueFrom)(data.search.search({
      params: getFindingsQuery(options, pageParam)
    }));
    if (!aggregations) throw new Error('expected aggregations to be an defined');
    if (!Array.isArray(aggregations.count.buckets)) throw new Error('expected buckets to be an array');
    return {
      page: hits.hits.map(hit => (0, _discoverUtils.buildDataTableRecord)(hit)),
      total: _ioTs.number.is(hits.total) ? hits.total : 0,
      count: (0, _utils.getAggregationCount)(aggregations.count.buckets)
    };
  }, {
    enabled: options.enabled,
    keepPreviousData: true,
    onError: err => (0, _show_error_toast.showErrorToast)(toasts, err),
    getNextPageParam: lastPage => {
      if (lastPage.page.length === 0) return undefined;
      return lastPage.page[lastPage.page.length - 1].raw.sort;
    }
  });
};
exports.useLatestFindings = useLatestFindings;