"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateTicket = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const validatePayloadAndCreateSdk_1 = require("../../lib/validatePayloadAndCreateSdk");
const config_1 = require("./config");
const addEventLog_1 = require("../../../../src/lib/awell/addEventLog");
const axios_1 = require("axios");
exports.updateTicket = {
    key: 'updateTicket',
    category: extensions_core_1.Category.CUSTOMER_SUPPORT,
    title: 'Update ticket',
    description: 'Update a ticket in Freshdesk.',
    fields: config_1.fields,
    previewable: false,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError }) => {
        var _a;
        const { fields, freshdeskSdk } = await (0, validatePayloadAndCreateSdk_1.validatePayloadAndCreateSdk)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        try {
            const ticketToUpdate = await freshdeskSdk.getTicket(fields.ticketId);
            const requestBody = {
                subject: fields.subject,
                type: fields.type,
                status: fields.status,
                priority: fields.priority,
                description: fields.description,
                due_by: fields.dueBy,
                tags: fields.tags,
                custom_fields: fields.customFields,
            };
            await freshdeskSdk.updateTicket({
                ticketId: fields.ticketId,
                input: requestBody,
            });
            await onComplete({
                events: [
                    (0, addEventLog_1.addActivityEventLog)({
                        message: `Ticket to update:\n${JSON.stringify(ticketToUpdate.data, null, 2)}`,
                    }),
                    (0, addEventLog_1.addActivityEventLog)({
                        message: `Ticket updated successfully with the following fields:\n${JSON.stringify(requestBody, null, 2)}`,
                    }),
                ],
            });
        }
        catch (error) {
            // Some errors we want to handle explicitly for more human-readable logging
            if (error instanceof axios_1.AxiosError) {
                const err = error;
                if (((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 404)
                    await onError({
                        events: [
                            (0, addEventLog_1.addActivityEventLog)({
                                message: 'Ticket to update not found (404)',
                            }),
                        ],
                    });
                return;
            }
            // Throw all other errors
            throw error;
        }
    },
};
//# sourceMappingURL=updateTicket.js.map