"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.addComment = void 0;
var _server = require("@kbn/core/server");
var _utils = require("../../../common/utils");
var _api = require("../../../common/types/api");
var _api2 = require("../../../common/api");
var _models = require("../../common/models");
var _error = require("../../common/error");
var _utils2 = require("../utils");
var _authorization = require("../../authorization");
var _validators = require("./validators");
/*
 * 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.
 */

/**
 * Create an attachment to a case.
 *
 * @ignore
 */
const addComment = async (addArgs, clientArgs) => {
  const {
    comment,
    caseId
  } = addArgs;
  const {
    logger,
    authorization,
    persistableStateAttachmentTypeRegistry,
    externalReferenceAttachmentTypeRegistry,
    services: {
      userActionService
    }
  } = clientArgs;
  try {
    const query = (0, _api2.decodeWithExcessOrThrow)(_api.AttachmentRequestRt)(comment);
    await (0, _utils.validateMaxUserActions)({
      caseId,
      userActionService,
      userActionsToAdd: 1
    });
    (0, _utils2.decodeCommentRequest)(comment, externalReferenceAttachmentTypeRegistry);
    const savedObjectID = _server.SavedObjectsUtils.generateId();
    await authorization.ensureAuthorized({
      operation: _authorization.Operations.createComment,
      entities: [{
        owner: comment.owner,
        id: savedObjectID
      }]
    });
    (0, _validators.validateRegisteredAttachments)({
      query,
      persistableStateAttachmentTypeRegistry,
      externalReferenceAttachmentTypeRegistry
    });
    const createdDate = new Date().toISOString();
    const model = await _models.CaseCommentModel.create(caseId, clientArgs);
    const updatedModel = await model.createComment({
      createdDate,
      commentReq: query,
      id: savedObjectID
    });
    return await updatedModel.encodeWithComments();
  } catch (error) {
    throw (0, _error.createCaseError)({
      message: `Failed while adding a comment to case id: ${caseId} error: ${error}`,
      error,
      logger
    });
  }
};
exports.addComment = addComment;