"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.find = void 0;
var _api = require("../../../common/types/api");
var _api2 = require("../../../common/api");
var _authorization = require("../../authorization");
var _utils = require("./utils");
var _error = require("../../common/error");
var _utils2 = require("../../common/utils");
var _runtime_types = require("../../../common/api/runtime_types");
/*
 * 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 find = async ({
  caseId,
  params
}, casesClient, clientArgs) => {
  const {
    services: {
      userActionService
    },
    logger,
    authorization
  } = clientArgs;
  try {
    // supertest and query-string encode a single entry in an array as just a string so make sure we have an array
    const types = (0, _utils2.asArray)(params.types);
    const queryParams = (0, _api2.decodeWithExcessOrThrow)(_api.UserActionFindRequestRt)({
      ...params,
      types
    });
    const [authorizationFilterRes] = await Promise.all([authorization.getAuthorizationFilter(_authorization.Operations.findUserActions),
    // ensure that we have authorization for reading the case
    casesClient.cases.resolve({
      id: caseId,
      includeComments: false
    })]);
    const {
      filter: authorizationFilter,
      ensureSavedObjectsAreAuthorized
    } = authorizationFilterRes;
    const userActions = await userActionService.finder.find({
      caseId,
      ...queryParams,
      filter: authorizationFilter
    });
    ensureSavedObjectsAreAuthorized(userActions.saved_objects.map(so => ({
      owner: so.attributes.owner,
      id: so.id
    })));
    const res = {
      userActions: (0, _utils.formatSavedObjects)(userActions),
      page: userActions.page,
      perPage: userActions.per_page,
      total: userActions.total
    };
    return (0, _runtime_types.decodeOrThrow)(_api.UserActionFindResponseRt)(res);
  } catch (error) {
    throw (0, _error.createCaseError)({
      message: `Failed to find user actions for case id: ${caseId}: ${error}`,
      error,
      logger
    });
  }
};
exports.find = find;