"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CaseConfigureService = void 0;
var _server = require("@kbn/actions-plugin/server");
var _constants = require("../../common/constants");
var _api = require("../../../common/api");
var _constants2 = require("../../../common/constants");
var _transform = require("../transform");
var _connector_reference_handler = require("../connector_reference_handler");
var _configure = require("../../common/types/configure");
/*
 * 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 CaseConfigureService {
  constructor(log) {
    this.log = log;
  }
  async delete({
    unsecuredSavedObjectsClient,
    configurationId,
    refresh
  }) {
    try {
      this.log.debug(`Attempting to DELETE case configure ${configurationId}`);
      await unsecuredSavedObjectsClient.delete(_constants2.CASE_CONFIGURE_SAVED_OBJECT, configurationId, {
        refresh
      });
    } catch (error) {
      this.log.debug(`Error on DELETE case configure ${configurationId}: ${error}`);
      throw error;
    }
  }
  async get({
    unsecuredSavedObjectsClient,
    configurationId
  }) {
    try {
      this.log.debug(`Attempting to GET case configuration ${configurationId}`);
      const configuration = await unsecuredSavedObjectsClient.get(_constants2.CASE_CONFIGURE_SAVED_OBJECT, configurationId);
      return transformToExternalAndValidate(configuration);
    } catch (error) {
      this.log.debug(`Error on GET case configuration ${configurationId}: ${error}`);
      throw error;
    }
  }
  async find({
    unsecuredSavedObjectsClient,
    options
  }) {
    try {
      this.log.debug(`Attempting to find all case configuration`);
      const findResp = await unsecuredSavedObjectsClient.find({
        ...options,
        // Get the latest configuration
        sortField: 'created_at',
        sortOrder: 'desc',
        type: _constants2.CASE_CONFIGURE_SAVED_OBJECT
      });
      const transformedConfigs = transformFindResponseToExternalModel(findResp);
      const validatedConfigs = [];
      for (const config of transformedConfigs.saved_objects) {
        const validatedAttributes = (0, _api.decodeOrThrow)(_configure.ConfigurationTransformedAttributesRt)(config.attributes);
        validatedConfigs.push(Object.assign(config, {
          attributes: validatedAttributes
        }));
      }
      return Object.assign(transformedConfigs, {
        saved_objects: validatedConfigs
      });
    } catch (error) {
      this.log.debug(`Attempting to find all case configuration`);
      throw error;
    }
  }
  async post({
    unsecuredSavedObjectsClient,
    attributes,
    id,
    refresh
  }) {
    try {
      this.log.debug(`Attempting to POST a new case configuration`);
      const decodedAttributes = (0, _api.decodeOrThrow)(_configure.ConfigurationTransformedAttributesRt)(attributes);
      const esConfigInfo = transformAttributesToESModel(decodedAttributes);
      const createdConfig = await unsecuredSavedObjectsClient.create(_constants2.CASE_CONFIGURE_SAVED_OBJECT, esConfigInfo.attributes, {
        id,
        references: esConfigInfo.referenceHandler.build(),
        refresh
      });
      return transformToExternalAndValidate(createdConfig);
    } catch (error) {
      this.log.debug(`Error on POST a new case configuration: ${error}`);
      throw error;
    }
  }
  async patch({
    unsecuredSavedObjectsClient,
    configurationId,
    updatedAttributes,
    originalConfiguration,
    refresh
  }) {
    try {
      this.log.debug(`Attempting to UPDATE case configuration ${configurationId}`);
      const decodedAttributes = (0, _api.decodeOrThrow)(_configure.ConfigurationPartialAttributesRt)(updatedAttributes);
      const esUpdateInfo = transformAttributesToESModel(decodedAttributes);
      const updatedConfiguration = await unsecuredSavedObjectsClient.update(_constants2.CASE_CONFIGURE_SAVED_OBJECT, configurationId, {
        ...esUpdateInfo.attributes
      }, {
        references: esUpdateInfo.referenceHandler.build(originalConfiguration.references),
        refresh
      });
      const transformedConfig = transformUpdateResponseToExternalModel(updatedConfiguration);
      const validatedAttributes = (0, _api.decodeOrThrow)(_configure.ConfigurationPartialAttributesRt)(transformedConfig.attributes);
      return Object.assign(transformedConfig, {
        attributes: validatedAttributes
      });
    } catch (error) {
      this.log.debug(`Error on UPDATE case configuration ${configurationId}: ${error}`);
      throw error;
    }
  }
}
exports.CaseConfigureService = CaseConfigureService;
const transformToExternalAndValidate = configuration => {
  const transformedConfig = transformToExternalModel(configuration);
  const validatedAttributes = (0, _api.decodeOrThrow)(_configure.ConfigurationTransformedAttributesRt)(transformedConfig.attributes);
  return Object.assign(transformedConfig, {
    attributes: validatedAttributes
  });
};
function transformUpdateResponseToExternalModel(updatedConfiguration) {
  var _updatedConfiguration;
  const {
    connector,
    ...restUpdatedAttributes
  } = (_updatedConfiguration = updatedConfiguration.attributes) !== null && _updatedConfiguration !== void 0 ? _updatedConfiguration : {};
  const transformedConnector = (0, _transform.transformESConnectorToExternalModel)({
    connector,
    references: updatedConfiguration.references,
    referenceName: _constants.CONNECTOR_ID_REFERENCE_NAME
  });
  const attributes = restUpdatedAttributes;
  return {
    ...updatedConfiguration,
    attributes: {
      ...attributes,
      ...(transformedConnector && {
        connector: transformedConnector
      })
    }
  };
}
function transformToExternalModel(configuration) {
  const connector = (0, _transform.transformESConnectorOrUseDefault)({
    connector: configuration.attributes.connector,
    references: configuration.references,
    referenceName: _constants.CONNECTOR_ID_REFERENCE_NAME
  });
  const castedAttributes = configuration.attributes;
  const customFields = !configuration.attributes.customFields ? [] : configuration.attributes.customFields;
  return {
    ...configuration,
    attributes: {
      ...castedAttributes,
      connector,
      customFields
    }
  };
}
function transformFindResponseToExternalModel(configurations) {
  return {
    ...configurations,
    saved_objects: configurations.saved_objects.map(so => ({
      ...so,
      ...transformToExternalModel(so)
    }))
  };
}
function transformAttributesToESModel(configuration) {
  const {
    connector,
    ...restWithoutConnector
  } = configuration;
  const transformedConnector = {
    ...(connector && {
      connector: {
        name: connector.name,
        type: connector.type,
        fields: (0, _transform.transformFieldsToESModel)(connector)
      }
    })
  };
  return {
    attributes: {
      ...restWithoutConnector,
      ...transformedConnector
    },
    referenceHandler: buildReferenceHandler(connector === null || connector === void 0 ? void 0 : connector.id)
  };
}
function buildReferenceHandler(id) {
  return new _connector_reference_handler.ConnectorReferenceHandler([{
    id,
    name: _constants.CONNECTOR_ID_REFERENCE_NAME,
    type: _server.ACTION_SAVED_OBJECT_TYPE
  }]);
}