"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateCustomerCustomFields = 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");
/**
 * @link https://sendbird.com/docs/desk/platform-api/v1/features/customer#2-update-custom-fields-of-a-customer
 */
exports.updateCustomerCustomFields = {
    key: 'updateCustomerCustomFields',
    title: "Update customer's custom fields",
    description: 'Updates custom fields of a customer using the Desk API.',
    category: extensions_core_1.Category.COMMUNICATION,
    fields: config_1.fields,
    previewable: false,
    onActivityCreated: async (payload, onComplete, onError) => {
        try {
            const { settings: { applicationId, chatApiToken, deskApiToken }, fields: { customerId, customFields }, } = (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,
            });
            const { data: { customFields: receivedCustomFields }, } = await client.deskApi.updateCustomerCustomFields(customerId, {
                customFields,
            });
            // check that all fields were updated
            try {
                const customFieldsObject = JSON.parse(customFields);
                const providedFields = Object.keys(customFieldsObject);
                const receivedFields = receivedCustomFields.map(({ key }) => key);
                const missingFields = receivedFields.filter((field) => !providedFields.includes(field));
                if (missingFields.length > 0) {
                    await onError({
                        events: [
                            {
                                date: new Date().toISOString(),
                                text: {
                                    en: `Some custom fields do not appear to have been set correctly`,
                                },
                                error: {
                                    category: 'WRONG_DATA',
                                    message: `The following fields were not updated: ${missingFields.join(', ')}`,
                                },
                            },
                        ],
                    });
                    return;
                }
            }
            catch (e) {
                // if we can't parse the JSON, we can't check if all fields were updated
                // so we just skip this check
            }
            // check that values match
            try {
                const customFieldsObject = JSON.parse(customFields);
                const fieldsWithMismatchedValues = Object.keys(customFieldsObject)
                    .filter((key) => {
                    var _a, _b;
                    const valueToSet = customFieldsObject[key];
                    const valueReceived = (_a = receivedCustomFields.find(({ key: receivedKey }) => key === receivedKey)) === null || _a === void 0 ? void 0 : _a.value;
                    try {
                        // check if value is a valid JSON
                        const parsedValueToSet = JSON.parse((_b = valueToSet) !== null && _b !== void 0 ? _b : '');
                        const parsedValueReceived = JSON.parse(valueReceived !== null && valueReceived !== void 0 ? valueReceived : '');
                        return !(0, lodash_1.isEqual)(parsedValueToSet, parsedValueReceived);
                    }
                    catch (e) {
                        // if not, compare as strings
                        return valueToSet !== valueReceived;
                    }
                })
                    .filter((value) => !(0, lodash_1.isNil)(value));
                if (fieldsWithMismatchedValues.length > 0) {
                    await onError({
                        events: [
                            {
                                date: new Date().toISOString(),
                                text: {
                                    en: `Some fields do not appear to have been correctly updated`,
                                },
                                error: {
                                    category: 'WRONG_DATA',
                                    message: `The following fields were not updated: ${fieldsWithMismatchedValues.join(', ')}`,
                                },
                            },
                        ],
                    });
                    return;
                }
            }
            catch (e) {
                // if we can't parse the JSON, we can't check if all fields were updated
                // so we just skip this check
            }
            // if all checks passed, we can assume that the update was successful
            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.isSendbirdDeskError)(err)) {
                const events = (0, client_1.sendbirdDeskErrorToActivityEvent)(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=updateCustomerCustomFields.js.map