"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.DataExtensionSchemaService = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _http = require("@wix/bex-utils/@wix/ambassador-data-extensions-v1-data-extension-schema/http");
var _updateDataExtensionSchemaErrors = require("./updateDataExtensionSchemaErrors");
var _createDataExtensionSchemaErrors = require("./createDataExtensionSchemaErrors");
var _deleteUserDefinedFieldsErrors = require("./deleteUserDefinedFieldsErrors");
// server types

// client types

class DataExtensionSchemaService {
  static toSchemaType(type) {
    switch (type) {
      case 'shortText':
        return {
          type: 'string',
          format: 'single-line',
          maxLength: 120
        };
      case 'longText':
        return {
          type: 'string',
          maxLength: 200
        };
      case 'url':
        return {
          type: 'string',
          format: 'uri',
          maxLength: 256
        };
      case 'date':
        return {
          type: 'string',
          format: 'date'
        };
      case 'dateTime':
        return {
          type: 'string',
          format: 'date-time'
        };
      case 'integer':
        return {
          type: 'integer'
        };
      case 'decimal':
        return {
          type: 'number'
        };
      case 'checkbox':
        return {
          type: 'boolean'
        };
      case 'dropdown':
        return {
          type: 'array',
          items: {
            type: 'string'
          }
        };
      default:
        throw new Error(`Unexpected type: ${type}`);
    }
  }
  static toCustomType(field) {
    switch (field.type) {
      case 'string':
        if (field.hasOwnProperty('enum')) {
          return 'dropdown';
        }
        switch (field.format) {
          case 'date-time':
            return 'dateTime';
          case 'uri':
            return 'url';
          case 'date':
            return 'date';
          case 'single-line':
            return 'shortText';
          default:
            return 'longText';
        }
      case 'number':
        return 'decimal';
      case 'integer':
        return 'integer';
      case 'boolean':
        return 'checkbox';
      case 'array':
        {
          var _field$items;
          if (((_field$items = field.items) == null ? void 0 : _field$items['x-wix-object-type']) === 'FILE/V1') {
            return 'files';
          }
          return 'multiSelect';
        }
      case 'object':
        {
          if (field['x-wix-object-type'] === 'FILE/V1') {
            return 'files';
          }
          return 'dropdown';
        }
      default:
        return;
    }
  }
  static toCustomField(schema, key) {
    var _schema$jsonSchema;
    const property = (_schema$jsonSchema = schema.jsonSchema) == null || (_schema$jsonSchema = _schema$jsonSchema.properties) == null ? void 0 : _schema$jsonSchema[key];
    if (!property || typeof property !== 'object') {
      return;
    }
    if (typeof property.title !== 'string' || typeof property.type !== 'string' || typeof property['x-wix-permissions'] !== 'object') {
      return;
    }
    return {
      ...property,
      id: key
    };
  }
  constructor(params) {
    (0, _defineProperty2.default)(this, "httpClient", void 0);
    (0, _defineProperty2.default)(this, "translate", void 0);
    (0, _defineProperty2.default)(this, "errorHandler", void 0);
    (0, _defineProperty2.default)(this, "userFieldsNamespace", '_user_fields');
    this.httpClient = params.httpClient;
    this.translate = params.translate;
    this.errorHandler = params.errorHandler;
  }
  addCustomField(params) {
    var _params$schema, _params$schema2, _params$schema3;
    const {
      userFieldsNamespace
    } = this;
    const {
      form: {
        key,
        name,
        readApps,
        readUsers,
        writeApps,
        writeUsers,
        containsPii
      },
      fqdn
    } = params;
    const type = DataExtensionSchemaService.toSchemaType(params.form.type);
    const permissions = {
      read: ['users', ...(readUsers ? ['users-of-users'] : []), ...(readApps ? ['apps'] : [])],
      write: ['users', ...(writeUsers ? ['users-of-users'] : []), ...(writeApps ? ['apps'] : [])]
    };
    const filterable = params.filterable ? {
      'x-wix-filterable': true
    } : {};
    const schema = {
      fqdn,
      namespace: userFieldsNamespace,
      ...params.schema,
      jsonSchema: {
        properties: {
          ...((_params$schema = params.schema) == null || (_params$schema = _params$schema.jsonSchema) == null ? void 0 : _params$schema.properties),
          [key]: {
            ...((_params$schema2 = params.schema) == null || (_params$schema2 = _params$schema2.jsonSchema) == null || (_params$schema2 = _params$schema2.properties) == null ? void 0 : _params$schema2[key]),
            title: name,
            ...(containsPii ? {
              'x-wix-pii': {
                enabled: true
              }
            } : {}),
            ...type,
            'x-wix-permissions': permissions,
            ...filterable
          }
        }
      }
    };
    return (_params$schema3 = params.schema) != null && _params$schema3.id ? this._updateDataExtensionSchema(schema) : this._createDataExtensionSchema(schema);
  }
  archiveCustomField(params) {
    var _params$schema4, _params$schema5;
    const {
      userFieldsNamespace
    } = this;
    const {
      id,
      fqdn
    } = params;
    const schema = {
      fqdn,
      namespace: userFieldsNamespace,
      ...params.schema,
      jsonSchema: {
        properties: {
          ...((_params$schema4 = params.schema) == null || (_params$schema4 = _params$schema4.jsonSchema) == null ? void 0 : _params$schema4.properties),
          [id]: {
            ...((_params$schema5 = params.schema) == null || (_params$schema5 = _params$schema5.jsonSchema) == null || (_params$schema5 = _params$schema5.properties) == null ? void 0 : _params$schema5[id]),
            'x-wix-archived': true
          }
        }
      }
    };
    return this._updateDataExtensionSchema(schema);
  }
  restoreCustomField(params) {
    var _params$schema6, _params$schema7;
    const {
      userFieldsNamespace
    } = this;
    const {
      id,
      fqdn
    } = params;
    const schema = {
      fqdn,
      namespace: userFieldsNamespace,
      ...params.schema,
      jsonSchema: {
        properties: {
          ...((_params$schema6 = params.schema) == null || (_params$schema6 = _params$schema6.jsonSchema) == null ? void 0 : _params$schema6.properties),
          [id]: {
            ...((_params$schema7 = params.schema) == null || (_params$schema7 = _params$schema7.jsonSchema) == null || (_params$schema7 = _params$schema7.properties) == null ? void 0 : _params$schema7[id]),
            'x-wix-archived': false
          }
        }
      }
    };
    return this._updateDataExtensionSchema(schema);
  }
  restoreDeletedField(params) {
    var _params$schema8;
    const {
      userFieldsNamespace
    } = this;
    const {
      id,
      fqdn,
      fieldData
    } = params;
    const schema = {
      fqdn,
      namespace: userFieldsNamespace,
      ...params.schema,
      jsonSchema: {
        properties: {
          ...((_params$schema8 = params.schema) == null || (_params$schema8 = _params$schema8.jsonSchema) == null ? void 0 : _params$schema8.properties),
          [id]: {
            ...fieldData,
            'x-wix-archived': true
          }
        }
      }
    };
    return this._updateDataExtensionSchema(schema);
  }
  deleteCustomField(params) {
    var _params$schema9, _params$schema$jsonSc;
    const {
      id
    } = params;
    if (!((_params$schema9 = params.schema) != null && _params$schema9.id)) {
      throw new Error('Schema ID is required to delete a custom field');
    }

    // Check if the field is archived before attempting deletion
    const field = (_params$schema$jsonSc = params.schema.jsonSchema) == null || (_params$schema$jsonSc = _params$schema$jsonSc.properties) == null ? void 0 : _params$schema$jsonSc[id];
    if (field && !field['x-wix-archived']) {
      throw new Error('Field must be archived before it can be deleted. Please archive the field first.');
    }
    return this._deleteUserDefinedFields(params.schema.id, [id]);
  }
  async fetchSchemas(fqdn) {
    const {
      httpClient,
      errorHandler
    } = this;
    const res = await errorHandler.withErrorHandler(() => httpClient.request((0, _http.listDataExtensionSchemas)({
      fqdn,
      namespaces: [],
      fields: ['ARCHIVED']
    })), {});
    return res.data;
  }
  async _createDataExtensionSchema(schema) {
    const {
      httpClient,
      errorHandler
    } = this;
    return errorHandler.withErrorHandler(() => httpClient.request((0, _http.createDataExtensionSchema)({
      dataExtensionSchema: schema
    })), (0, _createDataExtensionSchemaErrors.createDataExtensionSchemaErrors)({
      translate: this.translate
    })).then(res => res.data);
  }
  async _updateDataExtensionSchema(schema) {
    const {
      httpClient,
      errorHandler
    } = this;
    return errorHandler.withErrorHandler(() => httpClient.request((0, _http.updateDataExtensionSchema)({
      dataExtensionSchema: schema
    })), (0, _updateDataExtensionSchemaErrors.updateDataExtensionSchemaErrors)({
      translate: this.translate
    })).then(res => res.data);
  }
  async _deleteUserDefinedFields(dataExtensionSchemaId, fieldsToDelete) {
    const {
      httpClient,
      errorHandler
    } = this;
    return errorHandler.withErrorHandler(() => httpClient.request((0, _http.deleteUserDefinedFields)({
      dataExtensionSchemaId,
      fieldsToDelete
    })), (0, _deleteUserDefinedFieldsErrors.deleteUserDefinedFieldsErrors)({
      translate: this.translate
    })).then(res => res.data);
  }
}
exports.DataExtensionSchemaService = DataExtensionSchemaService;
//# sourceMappingURL=dataExtensionService.js.map