"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AttachmentLimitChecker = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _boom = _interopRequireDefault(require("@hapi/boom"));
var _alerts = require("./limiters/alerts");
var _files = require("./limiters/files");
var _persistable_state_and_external_references = require("./limiters/persistable_state_and_external_references");
/*
 * 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.
 */

class AttachmentLimitChecker {
  constructor(attachmentService, fileService, caseId) {
    (0, _defineProperty2.default)(this, "limiters", void 0);
    this.caseId = caseId;
    this.limiters = [new _alerts.AlertLimiter(attachmentService), new _files.FileLimiter(fileService), new _persistable_state_and_external_references.PersistableStateAndExternalReferencesLimiter(attachmentService)];
  }
  async validate(requests) {
    for (const limiter of this.limiters) {
      const itemsWithinRequests = limiter.countOfItemsInRequest(requests);
      const hasItemsInRequests = itemsWithinRequests > 0;
      const totalAfterRequests = async () => {
        const itemsWithinCase = await limiter.countOfItemsWithinCase(this.caseId);
        return itemsWithinRequests + itemsWithinCase;
      };

      /**
       * The call to totalAfterRequests is intentionally performed after checking the limit. If the number in the
       * requests is greater than the max then we can skip checking how many items exist within the case because it is
       * guaranteed to exceed.
       */
      if (hasItemsInRequests && (itemsWithinRequests > limiter.limit || (await totalAfterRequests()) > limiter.limit)) {
        throw _boom.default.badRequest(limiter.errorMessage);
      }
    }
  }
}
exports.AttachmentLimitChecker = AttachmentLimitChecker;