"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteMetadata = void 0;
const zod_1 = require("zod");
const zod_validation_error_1 = require("zod-validation-error");
const extensions_core_1 = require("@awell-health/extensions-core");
const settings_1 = require("../../../settings");
const config_1 = require("./config");
const client_1 = require("../../client");
const lodash_1 = require("lodash");
exports.deleteMetadata = {
    key: 'deleteMetadata',
    title: 'Delete metadata',
    description: 'Deletes metadata from a user using the Chat API.',
    category: extensions_core_1.Category.COMMUNICATION,
    fields: config_1.fields,
    previewable: true,
    onActivityCreated: async (payload, onComplete, onError) => {
        try {
            const { settings: { applicationId, chatApiToken, deskApiToken }, fields: { userId, metadataKey }, } = (0, extensions_core_1.validate)({
                schema: zod_1.z.object({
                    settings: settings_1.SettingsValidationSchema,
                    fields: config_1.FieldsValidationSchema,
                }),
                payload,
            });
            const client = new client_1.SendbirdClient({
                applicationId,
                chatApiToken,
                deskApiToken,
            });
            await client.chatApi.deleteMetadata(userId, !(0, lodash_1.isEmpty)(metadataKey) ? metadataKey : undefined);
            await onComplete();
        }
        catch (err) {
            if (err instanceof zod_1.ZodError) {
                const error = (0, zod_validation_error_1.fromZodError)(err);
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: { en: error.message },
                            error: {
                                category: 'WRONG_INPUT',
                                message: error.message,
                            },
                        },
                    ],
                });
            }
            else if ((0, client_1.isSendbirdChatError)(err)) {
                const events = (0, client_1.sendbirdChatErrorToActivityEvent)(err);
                await onError({ events });
            }
            else {
                const message = err.message;
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: { en: message },
                            error: {
                                category: 'SERVER_ERROR',
                                message,
                            },
                        },
                    ],
                });
            }
        }
    },
};
//# sourceMappingURL=deleteMetadata.js.map