"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.MAX_CUSTOM_FIELDS = exports.DataExtensionState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _services = require("../services");
var _TaskState = require("./TaskState");
var _mobx = require("mobx");
var _util = require("../util");
var _DataExtensionField = require("./DataExtension/DataExtensionField");
var _ConditionalModalState = require("./ConditionalModalState");
var _DeleteFieldModalState = require("./DeleteFieldModalState");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
const MAX_CUSTOM_FIELDS = exports.MAX_CUSTOM_FIELDS = 50;

/**
 * Manages data extension schemas and custom fields for a collection
 */
class DataExtensionState {
  get fqdnString() {
    return (0, _util.fqdnToString)(this.fqdn);
  }
  get isFqdnValid() {
    return this.fqdn.resource !== undefined;
  }
  constructor(params) {
    (0, _defineProperty2.default)(this, "dataExtensionService", void 0);
    (0, _defineProperty2.default)(this, "initTask", new _TaskState.TaskState());
    (0, _defineProperty2.default)(this, "container", void 0);
    (0, _defineProperty2.default)(this, "_hasWritePermissions", void 0);
    (0, _defineProperty2.default)(this, "closeSidePanel", void 0);
    (0, _defineProperty2.default)(this, "fqdn", void 0);
    (0, _defineProperty2.default)(this, "_dataExtensionSchemasBase", []);
    (0, _defineProperty2.default)(this, "containsPii", void 0);
    (0, _defineProperty2.default)(this, "defaultPermissions", void 0);
    (0, _defineProperty2.default)(this, "disableUserDefinedWriting", void 0);
    (0, _defineProperty2.default)(this, "filterable", void 0);
    (0, _defineProperty2.default)(this, "enableArchive", void 0);
    (0, _defineProperty2.default)(this, "isArchivedPanelOpen", false);
    // Lazy-loaded service for field operations (archive/restore/delete)
    (0, _defineProperty2.default)(this, "_fieldOperationsService", void 0);
    (0, _defineProperty2.default)(this, "_fieldOperationsServicePromise", void 0);
    (0, _defineProperty2.default)(this, "deleteConfirmModal", new _ConditionalModalState.ConditionalModalState());
    (0, _defineProperty2.default)(this, "deleteFieldModal", void 0);
    (0, _defineProperty2.default)(this, "_extensionPoint", void 0);
    this.container = params.container;
    this.disableUserDefinedWriting = params.disableUserDefinedWriting;
    this.filterable = params.filterable;
    this.enableArchive = params.enableArchive ?? true;
    this.closeSidePanel = params.closeSidePanel;
    this.fqdn = params.fqdn;
    this._extensionPoint = params.extensionPoint;
    this.dataExtensionService = new _services.DataExtensionSchemaService(params.container);
    this.containsPii = params.containsPii;
    this.defaultPermissions = params.defaultPermissions;

    // Initialize deleteFieldModal with proper reportBi
    this.deleteFieldModal = new _DeleteFieldModalState.DeleteFieldModalState({
      dataExtension: this,
      reportBi: params.container.createBILogger({
        componentType: 'DataExtension',
        ...params.fqdn
      })
    });
    (0, _mobx.makeObservable)(this, {
      allUserCustomFields: _mobx.computed,
      allAppsCustomFields: _mobx.computed,
      allCustomFields: _mobx.computed,
      archivedItems: _mobx.computed,
      shouldDisplayArchive: _mobx.computed,
      filterableCustomFields: _mobx.computed,
      availableUserCustomFields: _mobx.computed,
      availableAppsCustomFields: _mobx.computed,
      availableCustomFields: _mobx.computed,
      isReachedMaxCustomFields: _mobx.computed,
      disableAddCustomField: _mobx.computed,
      disableAddCustomFieldContent: _mobx.computed,
      _dataExtensionSchemasBase: _mobx.observable.ref,
      _dataExtensionSchemas: _mobx.computed,
      userSchema: _mobx.computed,
      appSchemas: _mobx.computed,
      _upsertSchema: _mobx.action,
      containsPii: _mobx.observable,
      defaultPermissions: _mobx.observable,
      isArchivedPanelOpen: _mobx.observable,
      deleteFieldModal: _mobx.observable.ref,
      openArchivedPanel: _mobx.action,
      closeArchivedPanel: _mobx.action,
      openDeleteConfirmModal: _mobx.action
    });
  }
  get hasWritePermissions() {
    if (this._hasWritePermissions == null) {
      this._hasWritePermissions = this.container.user.permissions.includes('DATA_EXTENSION_SCHEMA.WRITE');
    }
    return this._hasWritePermissions;
  }
  get disableAddCustomField() {
    return !this.hasWritePermissions || this.isReachedMaxCustomFields;
  }
  get disableAddCustomFieldContent() {
    if (!this.hasWritePermissions) {
      return this.container.translate('cairo.customFields.writePermission.tooltip');
    }
    if (this.isReachedMaxCustomFields) {
      return this.container.translate('cairo.customFields.maxFields.tooltip', {
        max: MAX_CUSTOM_FIELDS
      });
    }
    return '';
  }
  getArchiveSuccessToastMessage(fieldName) {
    return this.enableArchive && fieldName ? this.container.translate('cairo.customFields.archive.success.toast.enabled', {
      selectedField: fieldName
    }) : this.container.translate('cairo.customFields.archive.success.toast');
  }
  getArchiveSuccessToastAction() {
    return this.enableArchive ? {
      text: this.container.translate('cairo.customFields.archive.success.toast.CTA'),
      uiType: 'LINK',
      onClick: () => {
        var _this$openArchivedPan;
        return (_this$openArchivedPan = this.openArchivedPanel) == null ? void 0 : _this$openArchivedPan.call(this);
      }
    } : undefined;
  }

  /**
   * Lazily loads the field operations service to reduce bundle size.
   * Only loads when archive/restore/delete operations are needed.
   */
  async getFieldOperationsService() {
    if (this._fieldOperationsService) {
      return this._fieldOperationsService;
    }

    // Reuse the same promise if already loading
    if (this._fieldOperationsServicePromise) {
      return this._fieldOperationsServicePromise;
    }
    this._fieldOperationsServicePromise = Promise.resolve().then(() => _interopRequireWildcard(require('../services/DataExtensionFieldOperationsService'))).then(module => {
      const self = this;
      this._fieldOperationsService = new module.DataExtensionFieldOperationsService({
        container: this.container,
        dataExtensionService: this.dataExtensionService,
        get userSchema() {
          return self.userSchema;
        },
        fqdnString: this.fqdnString,
        enableArchive: this.enableArchive,
        extractFieldValuesFromSchema: this.extractFieldValuesFromSchema.bind(this),
        upsertSchema: this._upsertSchema.bind(this),
        openArchivedPanel: this.openArchivedPanel.bind(this)
      });
      return this._fieldOperationsService;
    });
    return this._fieldOperationsServicePromise;
  }
  async archiveField({
    id,
    origin,
    reportBi
  }) {
    const service = await this.getFieldOperationsService();
    return service.archiveField({
      id,
      origin,
      reportBi
    });
  }
  async restoreField({
    id,
    origin,
    reportBi
  }) {
    const service = await this.getFieldOperationsService();
    return service.restoreField({
      id,
      origin,
      reportBi
    });
  }
  async deleteField({
    id,
    origin,
    reportBi
  }) {
    const service = await this.getFieldOperationsService();
    return service.deleteField({
      id,
      origin,
      reportBi
    });
  }
  extractFieldValuesFromSchema(fieldId) {
    var _customField$xWixPi;
    if (!this.userSchema) {
      return;
    }
    const customField = _services.DataExtensionSchemaService.toCustomField(this.userSchema, fieldId);
    if (!customField || !customField.type || !customField.title) {
      return;
    }
    const {
      read,
      write
    } = customField['x-wix-permissions'];
    const isPiiField = (_customField$xWixPi = customField['x-wix-pii']) == null ? void 0 : _customField$xWixPi.enabled;
    const readApps = read == null ? void 0 : read.includes('apps');
    const readUsers = read == null ? void 0 : read.includes('users-of-users');
    const writeApps = write == null ? void 0 : write.includes('apps');
    const writeUsers = write == null ? void 0 : write.includes('users-of-users');
    return {
      type: _services.DataExtensionSchemaService.toCustomType(customField),
      name: customField.title,
      key: customField.id,
      readApps,
      readUsers,
      writeApps,
      writeUsers,
      containsPii: Boolean(isPiiField)
    };
  }
  _toCustomField({
    key,
    schema,
    editable,
    owner,
    namespace
  }) {
    var _schema$xWixPii;
    if (!_services.DataExtensionSchemaService.toCustomType(schema)) {
      return;
    }
    return {
      id: key,
      label: (schema == null ? void 0 : schema.title) || key,
      maxLength: schema == null ? void 0 : schema.maxLength,
      options: schema == null ? void 0 : schema.enum,
      type: _services.DataExtensionSchemaService.toCustomType(schema),
      editable,
      filterable: schema['x-wix-filterable'],
      owner,
      properties: (schema == null ? void 0 : schema.properties) ?? {},
      namespace,
      isPii: Boolean((_schema$xWixPii = schema['x-wix-pii']) == null ? void 0 : _schema$xWixPii.enabled),
      permissions: schema['x-wix-permissions']
    };
  }
  isSupportedFieldType(type) {
    if (!type) {
      return false;
    }
    return ['string', 'number', 'integer', 'boolean', 'array'].includes(type);
  }
  getAvailableCustomFieldsInSchema(properties, {
    editable,
    requiredPermissions,
    owner,
    namespace
  }) {
    const filteredFields = Object.keys(properties).filter(key => {
      const field = properties[key];
      const isAllowedType = this.isSupportedFieldType(field.type) || field.type === 'object' && field['x-wix-object-type'] === 'FILE/V1';
      const isPermitted = requiredPermissions == null || (0, _DataExtensionField.includesAllReadPermissions)(field, requiredPermissions);
      return !field['x-wix-archived'] && isAllowedType && isPermitted;
    });
    const sorted = filteredFields.sort((a, b) => {
      const aVal = new Date(properties[a]['x-wix-created-date']);
      const bVal = new Date(properties[b]['x-wix-created-date']);
      if (isNaN(bVal.valueOf()) || isNaN(aVal.valueOf())) {
        return 0;
      }
      return aVal.valueOf() - bVal.valueOf();
    });
    return sorted.map(key => this._toCustomField({
      key,
      schema: properties[key],
      editable,
      owner,
      namespace
    })).filter(Boolean);
  }

  /**
   * Available custom fields, excluding archived fields
   */
  get availableUserCustomFields() {
    var _this$userSchema;
    const properties = ((_this$userSchema = this.userSchema) == null || (_this$userSchema = _this$userSchema.jsonSchema) == null ? void 0 : _this$userSchema.properties) || {};
    return this.getAvailableCustomFieldsInSchema(properties, {
      editable: true,
      owner: 'user',
      namespace: '_user_fields'
    });
  }
  get availableAppsCustomFields() {
    var _this$appSchemas;
    return ((_this$appSchemas = this.appSchemas) == null ? void 0 : _this$appSchemas.reduce((prev, schema) => {
      return [...prev, ...this.getAvailableCustomFieldsForApp(schema)];
    }, [])) ?? [];
  }
  getSchemaAndFieldsByNamespace(namespace) {
    var _schema$jsonSchema;
    const {
      _dataExtensionSchemas,
      dataExtensionService: {
        userFieldsNamespace
      }
    } = this;
    const schema = _dataExtensionSchemas.find(s => s.namespace === namespace);
    if (!schema) {
      return {};
    }
    const isAppNamespace = namespace !== userFieldsNamespace;
    const fields = this.getAvailableCustomFieldsInSchema(((_schema$jsonSchema = schema.jsonSchema) == null ? void 0 : _schema$jsonSchema.properties) || {}, {
      editable: false,
      owner: isAppNamespace ? 'app' : 'user',
      namespace,
      requiredPermissions: isAppNamespace ? ['users'] : undefined
    });
    return {
      schema,
      fields
    };
  }
  getAvailableCustomFieldsForApp(appSchema) {
    var _appSchema$jsonSchema;
    const properties = ((_appSchema$jsonSchema = appSchema.jsonSchema) == null ? void 0 : _appSchema$jsonSchema.properties) || {};
    return this.getAvailableCustomFieldsInSchema(properties, {
      editable: false,
      requiredPermissions: ['users'],
      owner: 'app',
      namespace: appSchema.namespace
    });
  }
  get availableCustomFields() {
    return [...this.availableUserCustomFields, ...this.availableAppsCustomFields];
  }
  get allUserCustomFields() {
    var _this$userSchema2;
    const properties = ((_this$userSchema2 = this.userSchema) == null || (_this$userSchema2 = _this$userSchema2.jsonSchema) == null ? void 0 : _this$userSchema2.properties) || {};
    return Object.keys(properties).map(key => this._toCustomField({
      key,
      schema: properties[key],
      editable: true,
      owner: 'user',
      namespace: '_user_fields'
    })).filter(Boolean);
  }
  get allAppsCustomFields() {
    var _this$appSchemas2;
    return ((_this$appSchemas2 = this.appSchemas) == null ? void 0 : _this$appSchemas2.reduce((prev, appSchema) => {
      var _appSchema$jsonSchema2;
      const properties = (appSchema == null || (_appSchema$jsonSchema2 = appSchema.jsonSchema) == null ? void 0 : _appSchema$jsonSchema2.properties) || {};
      return prev.concat(Object.keys(properties).map(key => this._toCustomField({
        key,
        schema: properties[key],
        editable: false,
        owner: 'app',
        namespace: appSchema.namespace
      })).filter(Boolean));
    }, [])) ?? [];
  }
  get allCustomFields() {
    return [...this.allUserCustomFields, ...this.allAppsCustomFields];
  }
  get archivedItems() {
    var _userSchema$jsonSchem;
    const userSchema = this.userSchema;
    if (!(userSchema != null && (_userSchema$jsonSchem = userSchema.jsonSchema) != null && _userSchema$jsonSchem.properties)) {
      return [];
    }
    const properties = userSchema.jsonSchema.properties;
    return Object.keys(properties).filter(key => properties[key]['x-wix-archived']).map(key => {
      var _properties$key, _properties$key2;
      return {
        ...properties[key],
        id: key,
        label: ((_properties$key = properties[key]) == null ? void 0 : _properties$key.title) || key,
        isPii: Boolean((_properties$key2 = properties[key]) == null || (_properties$key2 = _properties$key2['x-wix-pii']) == null ? void 0 : _properties$key2.enabled)
      };
    });
  }
  get shouldDisplayArchive() {
    return this.enableArchive && this.archivedItems.length > 0;
  }
  get filterableCustomFields() {
    if (!this.filterable) {
      return [];
    }
    return this.availableCustomFields.filter(field => field.filterable);
  }
  get isReachedMaxCustomFields() {
    return this.allUserCustomFields.length >= MAX_CUSTOM_FIELDS;
  }
  get allNamespaces() {
    var _this$userSchema3;
    return [(_this$userSchema3 = this.userSchema) == null ? void 0 : _this$userSchema3.namespace, ...(this.appSchemas || []).map(schema => schema.namespace)].filter(Boolean);
  }
  init() {
    const {
      initTask
    } = this;
    initTask.runOnce(async () => {
      await this.fetchSchemas();
    });
    return () => {};
  }
  _upsertSchema(newSchema) {
    const {
      _dataExtensionSchemasBase
    } = this;
    const index = _dataExtensionSchemasBase.findIndex(schema => schema.namespace === (newSchema == null ? void 0 : newSchema.namespace));
    if (index === -1) {
      this._dataExtensionSchemasBase = [..._dataExtensionSchemasBase, newSchema];
    } else {
      this._dataExtensionSchemasBase = _dataExtensionSchemasBase.map(schema => schema.namespace === newSchema.namespace ? newSchema : schema);
    }
  }
  get userSchema() {
    const {
      _dataExtensionSchemas,
      dataExtensionService: {
        userFieldsNamespace
      }
    } = this;
    return _dataExtensionSchemas.find(s => s.namespace === userFieldsNamespace);
  }
  get _dataExtensionSchemas() {
    const {
      _extensionPoint,
      _dataExtensionSchemasBase
    } = this;
    return _dataExtensionSchemasBase.filter(s => _extensionPoint ? s.extensionPoint === _extensionPoint : s.extensionPoint == null || s.extensionPoint === 'ROOT');
  }
  get appSchemas() {
    const {
      _dataExtensionSchemas,
      dataExtensionService: {
        userFieldsNamespace
      }
    } = this;
    return _dataExtensionSchemas.filter(s => s.namespace !== userFieldsNamespace);
  }
  async fetchSchemas() {
    const {
      dataExtensionService
    } = this;
    if (this.isFqdnValid) {
      const {
        dataExtensionSchemas
      } = await dataExtensionService.fetchSchemas(this.fqdnString);
      (0, _mobx.runInAction)(() => {
        this._dataExtensionSchemasBase = dataExtensionSchemas ?? [];
      });
    }
  }
  openArchivedPanel() {
    if (this.enableArchive) {
      this.isArchivedPanelOpen = true;
    }
  }
  closeArchivedPanel() {
    this.isArchivedPanelOpen = false;
  }
  openDeleteConfirmModal({
    id,
    origin
  }) {
    this.deleteConfirmModal.open({
      id,
      origin
    });
  }
}
exports.DataExtensionState = DataExtensionState;
//# sourceMappingURL=DataExtensionState.js.map