"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTicket = 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.createTicket = {
    key: 'createTicket',
    title: 'Create ticket',
    description: 'Creates a ticket using the Desk API.',
    category: extensions_core_1.Category.COMMUNICATION,
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: false,
    onActivityCreated: async (payload, onComplete, onError) => {
        var _a;
        try {
            const { settings: { applicationId, chatApiToken, deskApiToken }, fields: { customerId, channelName, groupKey, priority, customFields, relatedChannelUrls, }, } = (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 res = await client.deskApi.createTicket({
                customerId,
                channelName,
                groupKey,
                priority,
                customFields,
                relatedChannelUrls,
            });
            const { data: { id, channelUrl, relatedChannels }, } = res;
            /**
             * Array data point types not supported yet so storing as a comma-separated string
             */
            const relatedChannelUrlsArray = (0, lodash_1.isEmpty)(relatedChannels) || (0, lodash_1.isNil)(relatedChannels)
                ? undefined
                : JSON.parse(relatedChannels);
            const relatedChannelUrlsDataPoint = (_a = relatedChannelUrlsArray === null || relatedChannelUrlsArray === void 0 ? void 0 : relatedChannelUrlsArray.map((value) => value.channel_url).join(',')) !== null && _a !== void 0 ? _a : undefined;
            await onComplete({
                data_points: {
                    ticketId: String(id),
                    channelUrl,
                    relatedChannelUrls: relatedChannelUrlsDataPoint,
                },
            });
        }
        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=createTicket.js.map