import { createDataExtensionSchema, listDataExtensionSchemas, updateDataExtensionSchema, deleteUserDefinedFields, } from '@wix/bex-utils/@wix/ambassador-data-extensions-v1-data-extension-schema/http';
import { updateDataExtensionSchemaErrors } from './updateDataExtensionSchemaErrors';
import { createDataExtensionSchemaErrors } from './createDataExtensionSchemaErrors';
import { deleteUserDefinedFieldsErrors } from './deleteUserDefinedFieldsErrors';
export 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': {
                if (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) {
        const property = schema.jsonSchema?.properties?.[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) {
        this.userFieldsNamespace = '_user_fields';
        this.httpClient = params.httpClient;
        this.translate = params.translate;
        this.errorHandler = params.errorHandler;
    }
    addCustomField(params) {
        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?.jsonSchema?.properties,
                    [key]: {
                        ...params.schema?.jsonSchema?.properties?.[key],
                        title: name,
                        ...(containsPii ? { 'x-wix-pii': { enabled: true } } : {}),
                        ...type,
                        'x-wix-permissions': permissions,
                        ...filterable,
                    },
                },
            },
        };
        return params.schema?.id
            ? this._updateDataExtensionSchema(schema)
            : this._createDataExtensionSchema(schema);
    }
    archiveCustomField(params) {
        const { userFieldsNamespace } = this;
        const { id, fqdn } = params;
        const schema = {
            fqdn,
            namespace: userFieldsNamespace,
            ...params.schema,
            jsonSchema: {
                properties: {
                    ...params.schema?.jsonSchema?.properties,
                    [id]: {
                        ...params.schema?.jsonSchema?.properties?.[id],
                        'x-wix-archived': true,
                    },
                },
            },
        };
        return this._updateDataExtensionSchema(schema);
    }
    restoreCustomField(params) {
        const { userFieldsNamespace } = this;
        const { id, fqdn } = params;
        const schema = {
            fqdn,
            namespace: userFieldsNamespace,
            ...params.schema,
            jsonSchema: {
                properties: {
                    ...params.schema?.jsonSchema?.properties,
                    [id]: {
                        ...params.schema?.jsonSchema?.properties?.[id],
                        'x-wix-archived': false,
                    },
                },
            },
        };
        return this._updateDataExtensionSchema(schema);
    }
    restoreDeletedField(params) {
        const { userFieldsNamespace } = this;
        const { id, fqdn, fieldData } = params;
        const schema = {
            fqdn,
            namespace: userFieldsNamespace,
            ...params.schema,
            jsonSchema: {
                properties: {
                    ...params.schema?.jsonSchema?.properties,
                    [id]: {
                        ...fieldData,
                        'x-wix-archived': true,
                    },
                },
            },
        };
        return this._updateDataExtensionSchema(schema);
    }
    deleteCustomField(params) {
        const { id } = params;
        if (!params.schema?.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.jsonSchema?.properties?.[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(listDataExtensionSchemas({
            fqdn,
            namespaces: [],
            fields: ['ARCHIVED'],
        })), {});
        return res.data;
    }
    async _createDataExtensionSchema(schema) {
        const { httpClient, errorHandler } = this;
        return errorHandler
            .withErrorHandler(() => httpClient.request(createDataExtensionSchema({ dataExtensionSchema: schema })), createDataExtensionSchemaErrors({
            translate: this.translate,
        }))
            .then((res) => res.data);
    }
    async _updateDataExtensionSchema(schema) {
        const { httpClient, errorHandler } = this;
        return errorHandler
            .withErrorHandler(() => httpClient.request(updateDataExtensionSchema({ dataExtensionSchema: schema })), updateDataExtensionSchemaErrors({
            translate: this.translate,
        }))
            .then((res) => res.data);
    }
    async _deleteUserDefinedFields(dataExtensionSchemaId, fieldsToDelete) {
        const { httpClient, errorHandler } = this;
        return errorHandler
            .withErrorHandler(() => httpClient.request(deleteUserDefinedFields({
            dataExtensionSchemaId,
            fieldsToDelete,
        })), deleteUserDefinedFieldsErrors({
            translate: this.translate,
        }))
            .then((res) => res.data);
    }
}
//# sourceMappingURL=dataExtensionService.js.map