import { DataExtensionStateBIReporter } from '../state/DataExtensionStateBIReporter';
/**
 * Service for handling archive, restore, and delete operations on custom fields.
 * This service is lazily loaded to reduce bundle size for consumers who don't use these features.
 */
export class DataExtensionFieldOperationsService {
    constructor(context) {
        this.context = context;
    }
    showFieldOperationToast({ type, operation, message, action, onRetryClick, biName, }) {
        const { container } = this.context;
        const retryAction = {
            uiType: 'LINK',
            text: container.translate('cairo.toast.retry'),
            onClick: onRetryClick,
            removeToastOnClick: true,
        };
        container.showToast?.({
            message,
            action: type !== 'SUCCESS' && onRetryClick ? retryAction : action,
            type,
            biName: biName || `cairo-${operation}-custom-field-${type.toLowerCase()}-toast`,
        });
    }
    async archiveField({ id, origin, reportBi }) {
        if (!id) {
            return;
        }
        const { dataExtensionService, userSchema, fqdnString, extractFieldValuesFromSchema, upsertSchema, container, enableArchive, openArchivedPanel, } = this.context;
        const fieldValues = extractFieldValuesFromSchema(id);
        const fieldName = fieldValues?.name || '';
        const biReporter = new DataExtensionStateBIReporter({ reportBi });
        try {
            const { dataExtensionSchema } = await dataExtensionService.archiveCustomField({
                schema: userSchema,
                fqdn: fqdnString,
                id,
            });
            if (dataExtensionSchema) {
                upsertSchema(dataExtensionSchema);
            }
            const successMessage = enableArchive && fieldName
                ? container.translate('cairo.customFields.archive.success.toast.enabled', { selectedField: fieldName })
                : container.translate('cairo.customFields.archive.success.toast');
            const action = enableArchive
                ? {
                    text: container.translate('cairo.customFields.archive.success.toast.CTA'),
                    uiType: 'LINK',
                    onClick: () => openArchivedPanel?.(),
                }
                : undefined;
            this.showFieldOperationToast({
                type: 'SUCCESS',
                operation: 'archive',
                message: successMessage,
                action,
            });
        }
        catch (e) {
            this.showFieldOperationToast({
                type: 'ERROR',
                operation: 'archive',
                message: container.translate('cairo.customFields.archive.error.toast', {
                    selectedField: fieldName,
                }),
                onRetryClick: () => {
                    biReporter.reportArchiveTryAgain();
                    this.archiveField({ id, origin, reportBi });
                },
            });
            biReporter.reportArchiveFieldFailed({ formValues: fieldValues, origin });
        }
    }
    async restoreField({ id, origin, reportBi }) {
        if (!id) {
            return;
        }
        const { dataExtensionService, userSchema, fqdnString, extractFieldValuesFromSchema, upsertSchema, container, } = this.context;
        const fieldValues = extractFieldValuesFromSchema(id);
        const fieldName = fieldValues?.name || '';
        const biReporter = new DataExtensionStateBIReporter({ reportBi });
        try {
            const { dataExtensionSchema } = await dataExtensionService.restoreCustomField({
                schema: userSchema,
                fqdn: fqdnString,
                id,
            });
            if (dataExtensionSchema) {
                upsertSchema(dataExtensionSchema);
            }
            this.showFieldOperationToast({
                type: 'SUCCESS',
                operation: 'restore',
                message: container.translate('cairo.customFields.restored.success.toast', { selectedField: fieldName }),
            });
        }
        catch (e) {
            this.showFieldOperationToast({
                type: 'ERROR',
                operation: 'restore',
                message: container.translate('cairo.customFields.restore.error.toast', {
                    selectedField: fieldName,
                }),
                onRetryClick: () => {
                    biReporter.reportRestoreTryAgain();
                    this.restoreField({ id, origin, reportBi });
                },
            });
            biReporter.reportRestoreFieldFailed({ formValues: fieldValues, origin });
        }
    }
    async undoDeletedField({ id, fieldData, origin, reportBi, }) {
        if (!id) {
            return;
        }
        const { dataExtensionService, userSchema, fqdnString, upsertSchema, container, } = this.context;
        const fieldName = fieldData?.title || '';
        try {
            // Re-add the field to the schema in archived state
            const { dataExtensionSchema } = await dataExtensionService.restoreDeletedField({
                schema: userSchema,
                fqdn: fqdnString,
                id,
                fieldData,
            });
            if (dataExtensionSchema) {
                upsertSchema(dataExtensionSchema);
            }
            this.showFieldOperationToast({
                type: 'SUCCESS',
                operation: 'restore',
                message: container.translate('cairo.customFields.restored.success.toast', { selectedField: fieldName }),
            });
        }
        catch (e) {
            this.showFieldOperationToast({
                type: 'ERROR',
                operation: 'restore',
                message: container.translate('cairo.customFields.restore.error.toast', {
                    selectedField: fieldName,
                }),
                onRetryClick: () => this.undoDeletedField({ id, fieldData, origin, reportBi }),
            });
        }
    }
    async deleteField({ id, origin, reportBi }) {
        if (!id) {
            return;
        }
        const { dataExtensionService, userSchema, fqdnString, extractFieldValuesFromSchema, upsertSchema, container, } = this.context;
        const fieldValues = extractFieldValuesFromSchema(id);
        const fieldName = fieldValues?.name || '';
        // Validate field is archived
        const field = userSchema?.jsonSchema?.properties?.[id];
        if (field && !field['x-wix-archived']) {
            this.showFieldOperationToast({
                type: 'ERROR',
                operation: 'delete',
                message: `${fieldName || 'Field'} must be archived before it can be deleted.`,
                biName: 'cairo-delete-custom-field-not-archived-error-toast',
            });
            return;
        }
        // Store the field data before deletion for undo functionality
        const fieldDataBeforeDeletion = field ? { ...field } : null;
        try {
            const { dataExtensionSchema } = await dataExtensionService.deleteCustomField({
                schema: userSchema,
                fqdn: fqdnString,
                id,
            });
            if (dataExtensionSchema) {
                upsertSchema(dataExtensionSchema);
            }
            this.showFieldOperationToast({
                type: 'SUCCESS',
                operation: 'delete',
                message: container.translate('cairo.customFields.deleted.success.toast', { selectedField: fieldName }),
                action: fieldDataBeforeDeletion
                    ? {
                        uiType: 'LINK',
                        text: container.translate('cairo.toast.undo'),
                        onClick: () => this.undoDeletedField({
                            id,
                            fieldData: fieldDataBeforeDeletion,
                            origin,
                            reportBi,
                        }),
                        removeToastOnClick: true,
                    }
                    : undefined,
            });
        }
        catch (e) {
            this.showFieldOperationToast({
                type: 'ERROR',
                operation: 'delete',
                message: container.translate('cairo.customFields.delete.error.toast', {
                    selectedField: fieldName,
                }),
                onRetryClick: () => this.deleteField({ id, origin, reportBi }),
            });
        }
    }
}
//# sourceMappingURL=DataExtensionFieldOperationsService.js.map