"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateTicket = 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.updateTicket = {
    key: 'updateTicket',
    title: 'Update ticket',
    description: 'Updates an existing support ticket in Zendesk',
    category: extensions_core_1.Category.CUSTOMER_SUPPORT,
    fields: config_1.fields,
    previewable: true,
    onEvent: async ({ payload, onComplete, onError, helpers }) => {
        try {
            const { settings, fields: { ticket_id, comment, priority, status }, } = (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 updateData = {
                ...(!(0, lodash_1.isNil)(comment) && { comment: { body: comment } }),
                ...(!(0, lodash_1.isNil)(priority) && { priority }),
                ...(!(0, lodash_1.isNil)(status) && { status }),
            };
            await client.updateTicket(ticket_id.toString(), updateData);
            await onComplete({});
        }
        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 update ticket: ${errorMessage}` },
                            error: {
                                category: 'SERVER_ERROR',
                                message: errorMessage,
                            },
                        },
                    ],
                });
            }
        }
    },
};
//# sourceMappingURL=updateTicket.js.map