"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createChartingNote = void 0;
const lodash_1 = require("lodash");
const extensions_core_1 = require("@awell-health/extensions-core");
const sdk_1 = require("../../lib/sdk/graphql-codegen/generated/sdk");
const graphqlClient_1 = require("../../lib/sdk/graphql-codegen/graphqlClient");
const errors_1 = require("../../lib/sdk/graphql-codegen/errors");
const config_1 = require("./config");
const addEventLog_1 = require("../../../../src/lib/awell/addEventLog");
exports.createChartingNote = {
    key: 'createChartingNote',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Create charting note',
    description: 'Create a charting note in Healthie.',
    fields: config_1.fields,
    previewable: true,
    onActivityCreated: async (payload, onComplete, onError) => {
        var _a;
        const { fields, settings } = payload;
        const { healthie_patient_id, form_id, note_content, marked_locked, appointment_id, } = fields;
        try {
            if ((0, lodash_1.isNil)(healthie_patient_id) || (0, lodash_1.isNil)(form_id) || (0, lodash_1.isNil)(note_content)) {
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: { en: 'Fields are missing' },
                            error: {
                                category: 'MISSING_FIELDS',
                                message: '`healthie_patient_id`, `form_id` or `note_content` is missing',
                            },
                        },
                    ],
                });
                return;
            }
            const client = (0, graphqlClient_1.initialiseClient)(settings);
            if (client !== undefined) {
                const sdk = (0, sdk_1.getSdk)(client);
                const { data } = await sdk.getFormTemplate({
                    id: form_id,
                });
                const moduleForm = data.customModuleForm;
                if ((0, lodash_1.isNil)(moduleForm)) {
                    await onError({
                        events: [
                            (0, addEventLog_1.addActivityEventLog)({
                                message: `Note content: ${note_content}`,
                            }),
                            {
                                date: new Date().toISOString(),
                                text: { en: "Form doesn't exist" },
                                error: {
                                    category: 'WRONG_INPUT',
                                    message: `Form with id ${form_id} doesn't exist`,
                                },
                            },
                        ],
                    });
                    return;
                }
                if (!moduleForm.use_for_charting) {
                    await onError({
                        events: [
                            {
                                date: new Date().toISOString(),
                                text: { en: "Form isn't a charting form" },
                                error: {
                                    category: 'SERVER_ERROR',
                                    message: `Form with id ${form_id} cannot be used for charting`,
                                },
                            },
                        ],
                    });
                    return;
                }
                const firstTextAreaField = (_a = moduleForm.custom_modules) === null || _a === void 0 ? void 0 : _a.find(({ mod_type }) => mod_type === 'textarea');
                if ((0, lodash_1.isNil)(firstTextAreaField)) {
                    await onError({
                        events: [
                            {
                                date: new Date().toISOString(),
                                text: {
                                    en: 'Form doesn\'t have a question of type "textarea" (long text).',
                                },
                                error: {
                                    category: 'WRONG_DATA',
                                    message: `Form with id ${form_id}  doesn't have a "textarea" field`,
                                },
                            },
                        ],
                    });
                    return;
                }
                await sdk.createFormAnswerGroup({
                    input: {
                        finished: true,
                        custom_module_form_id: form_id,
                        user_id: healthie_patient_id,
                        appointment_id,
                        form_answers: [
                            {
                                custom_module_id: firstTextAreaField.id,
                                user_id: healthie_patient_id,
                                answer: note_content,
                            },
                        ],
                        marked_locked: marked_locked !== null && marked_locked !== void 0 ? marked_locked : false,
                    },
                });
                await onComplete({
                    events: [
                        (0, addEventLog_1.addActivityEventLog)({
                            message: `Note content: ${note_content}`,
                        }),
                    ],
                });
            }
            else {
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: { en: 'API client requires an API url and API key' },
                            error: {
                                category: 'MISSING_SETTINGS',
                                message: 'Missing api url or api key',
                            },
                        },
                    ],
                });
            }
        }
        catch (err) {
            if (err instanceof errors_1.HealthieError) {
                const errors = (0, errors_1.mapHealthieToActivityError)(err.errors);
                await onError({
                    events: errors,
                });
            }
            else {
                const error = err;
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: { en: 'Healthie API reported an error' },
                            error: {
                                category: 'SERVER_ERROR',
                                message: error.message,
                            },
                        },
                    ],
                });
            }
        }
    },
};
//# sourceMappingURL=createChartingNote.js.map