"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNonVisitNote = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const client_1 = require("../../client");
const axios_1 = require("axios");
const nonVisitNote_zod_1 = require("../../validation/nonVisitNote.zod");
const config_1 = require("./config");
const addEventLog_1 = require("../../../../src/lib/awell/addEventLog");
exports.createNonVisitNote = {
    key: 'createNonVisitNote',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Create Non-Visit Note',
    description: "Create a Non-Visit Note using Elation's patient API.",
    fields: config_1.fields,
    previewable: true,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError, helpers }) => {
        var _a, _b, _c;
        const { patientId, authorId, tags, text, category } = config_1.FieldsValidationSchema.parse(payload.fields);
        const awellSdk = await helpers.awellSdk();
        const escapedPlainText = awellSdk.utils.awell.slateToEscapedJsString(text, {
            paragraphSpacing: 'single',
        }); // Strip any HTML from the text
        const unescapedPlainText = escapedPlainText
            .replace(/\\n/g, '\n')
            .replace(/\\t/g, '\t')
            .replace(/\\"/g, '"')
            .replace(/\\\\/g, '\\');
        const note = nonVisitNote_zod_1.nonVisitNoteSchema.parse({
            tags,
            patient: patientId,
            bullets: [{ text: unescapedPlainText, author: authorId, category }],
            document_date: new Date().toISOString(),
            chart_date: new Date().toISOString(),
        });
        const api = (0, client_1.makeAPIClient)(payload.settings);
        try {
            const { data: { id, bullets }, } = await api.createNonVisitNote(note);
            await onComplete({
                data_points: {
                    nonVisitNoteId: String(id),
                    nonVisitNoteBulletId: String(bullets[0].id),
                },
            });
        }
        catch (err) {
            if (err instanceof axios_1.AxiosError) {
                await onError({
                    events: [
                        (0, addEventLog_1.addActivityEventLog)({
                            message: `${String((_a = err.response) === null || _a === void 0 ? void 0 : _a.status)}: ${String((_b = err.response) === null || _b === void 0 ? void 0 : _b.statusText)}\n${JSON.stringify((_c = err.response) === null || _c === void 0 ? void 0 : _c.data, null, 2)}`,
                        }),
                    ],
                });
                return;
            }
            throw err;
        }
    },
};
//# sourceMappingURL=createNonVisitNote.js.map