"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ticketCreated = void 0;
const settings_1 = require("../../settings");
const types_1 = require("./types");
const client_1 = require("../../lib/api/client");
const lodash_1 = require("lodash");
const dataPoints = {
    ticketId: {
        key: 'ticketId',
        valueType: 'string',
    },
};
exports.ticketCreated = {
    key: 'ticketCreated',
    dataPoints,
    onEvent: async ({ payload: { payload, rawBody, headers, settings }, onSuccess, onError, }) => {
        var _a;
        const parsedPayload = types_1.zTicketCreatedWebhookPayload.safeParse(payload);
        if (!parsedPayload.success) {
            await onError({
                response: {
                    statusCode: 400,
                    message: JSON.stringify(parsedPayload.error, null, 2),
                },
            });
            return;
        }
        const parsedSettings = settings_1.SettingsValidationSchema.safeParse(settings);
        if (!parsedSettings.success) {
            await onError({
                response: {
                    statusCode: 400,
                    message: JSON.stringify(parsedSettings.error, null, 2),
                },
            });
            return;
        }
        const baseUrl = `https://${parsedSettings.data.domain}.freshdesk.com/api/v2`;
        const freshdeskSdk = new client_1.FreshdeskApiClient({
            baseUrl,
            apiKey: parsedSettings.data.apiKey,
        });
        const ticket = await freshdeskSdk.getTicket(parsedPayload.data.freshdesk_webhook.ticket_id.toString());
        const requesterId = (_a = ticket.data) === null || _a === void 0 ? void 0 : _a.requester_id; // requested ID is the ID of the Freshdesk contact/patient
        await onSuccess({
            data_points: {
                ticketId: parsedPayload.data.freshdesk_webhook.ticket_id.toString(),
            },
            ...(!(0, lodash_1.isNil)(requesterId) && {
                patient_identifier: {
                    system: settings_1.FRESHDESK_IDENTIFIER_SYSTEM,
                    value: ticket.data.requester_id.toString(),
                },
            }),
        });
    },
};
//# sourceMappingURL=ticketCreated.js.map