"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.addNoteToTicket = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const validatePayloadAndCreateSdk_1 = require("../../lib/validatePayloadAndCreateSdk");
const config_1 = require("./config");
const axios_1 = require("axios");
const addEventLog_1 = require("../../../../src/lib/awell/addEventLog");
exports.addNoteToTicket = {
    key: 'addNoteToTicket',
    category: extensions_core_1.Category.CUSTOMER_SUPPORT,
    title: 'Add note to ticket',
    description: 'Add a note to a ticket in Freshdesk.',
    fields: config_1.fields,
    previewable: true,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError }) => {
        var _a, _b, _c;
        const { fields, freshdeskSdk } = await (0, validatePayloadAndCreateSdk_1.validatePayloadAndCreateSdk)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        try {
            await freshdeskSdk.addNote({
                ticketId: fields.ticketId,
                input: {
                    body: fields.body,
                    incoming: fields.incoming,
                    notify_emails: fields.notifyEmails,
                    private: fields.private,
                    user_id: fields.userId,
                },
            });
            await onComplete();
        }
        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 add note to not found (404)',
                            }),
                        ],
                    });
                    return;
                }
                if (((_b = err.response) === null || _b === void 0 ? void 0 : _b.status) === 400) {
                    await onError({
                        events: [
                            (0, addEventLog_1.addActivityEventLog)({
                                message: `Bad request (400): ${JSON.stringify((_c = err.response) === null || _c === void 0 ? void 0 : _c.data, null, 2)}`,
                            }),
                        ],
                    });
                    return;
                }
                // Throw unhandled Axios errors
                throw error;
            }
            // Throw all other errors
            throw error;
        }
    },
};
//# sourceMappingURL=addNoteToTicket.js.map