"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTicket = void 0;
const zod_1 = require("zod");
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 error_1 = require("../../client/error");
const lodash_1 = require("lodash");
exports.createTicket = {
    key: 'createTicket',
    title: 'Create ticket',
    description: 'Creates a new support ticket in Zendesk',
    category: extensions_core_1.Category.CUSTOMER_SUPPORT,
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: false,
    onEvent: async ({ payload, onComplete, onError }) => {
        try {
            const { settings, fields: { subject, comment, group_id, priority, external_id, tag }, } = (0, extensions_core_1.validate)({
                schema: zod_1.z.object({
                    settings: settings_1.SettingsValidationSchema,
                    fields: config_1.FieldsValidationSchema,
                }),
                payload,
            });
            const client = (0, client_1.makeAPIClient)(settings);
            const ticketData = {
                subject,
                comment: { body: comment },
                ...(!(0, lodash_1.isNil)(group_id) && { group_id: Number(group_id) }),
                ...(!(0, lodash_1.isNil)(priority) && { priority }),
                ...(!(0, lodash_1.isNil)(external_id) && { external_id }),
                ...(!(0, lodash_1.isNil)(tag) && { tags: [tag] }),
            };
            const response = await client.createTicket(ticketData);
            await onComplete({
                data_points: {
                    ticketId: response.ticket.id.toString(),
                    ticketUrl: `https://${settings.subdomain}.zendesk.com/agent/tickets/${response.ticket.id}`,
                },
            });
        }
        catch (err) {
            if ((0, error_1.isZendeskApiError)(err)) {
                const events = (0, error_1.zendeskApiErrorToActivityEvent)(err);
                await onError({ events });
            }
            else {
                const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: { en: `Failed to create ticket: ${errorMessage}` },
                            error: {
                                category: 'SERVER_ERROR',
                                message: errorMessage,
                            },
                        },
                    ],
                });
            }
        }
    },
};
//# sourceMappingURL=createTicket.js.map