"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pushFormResponseToHealthie = void 0;
const awell_1 = require("../../../../../src/lib/awell");
const extensions_core_1 = require("@awell-health/extensions-core");
const validatePayloadAndCreateSdk_1 = require("../../../lib/sdk/validatePayloadAndCreateSdk");
const config_1 = require("./config");
const logs_1 = require("./logs");
const lodash_1 = require("lodash");
const errors_1 = require("../shared/errors");
const errors_2 = require("../../../lib/sdk/graphql-codegen/errors");
exports.pushFormResponseToHealthie = {
    key: 'pushFormResponseToHealthie',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Push form response to Healthie',
    description: 'Pushes an Awell form response to a Healthie form',
    fields: config_1.fields,
    previewable: false,
    dataPoints: config_1.datapoints,
    onEvent: async ({ payload, onComplete, onError, helpers }) => {
        var _a, _b;
        const { fields, pathway, activity, healthieSdk } = await (0, validatePayloadAndCreateSdk_1.validatePayloadAndCreateSdk)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        const awellSdk = await helpers.awellSdk();
        /**
         * Returns the last completed form in a step at the time
         * the current activity in that step is activated.
         *
         * Example:
         * - Form 1 (completed)
         * - Form 2 (completed)
         * - Current activity
         * - Form 3 (not activated yet thus not-completed)
         *
         * Outcome:
         * Will return the `formDefinition` and `formResponse` of Form 2.
         */
        const { formDefinition, formResponse } = await (0, awell_1.getLatestFormInCurrentStep)({
            awellSdk,
            pathwayId: pathway.id,
            activityId: activity.id,
        });
        const { formAnswers: healthieFormAnswerInputs, omittedFormAnswers } = awellSdk.utils.healthie.awellFormResponseToHealthieFormAnswers({
            awellFormDefinition: formDefinition,
            awellFormResponse: formResponse,
        });
        // indicates whether to make form values editable in Healthie
        const lock = (0, lodash_1.defaultTo)(fields.lockFormAnswerGroup, false);
        try {
            const res = await healthieSdk.client.mutation({
                createFormAnswerGroup: {
                    __args: {
                        input: {
                            finished: true,
                            custom_module_form_id: fields.healthieFormId,
                            user_id: fields.healthiePatientId,
                            form_answers: healthieFormAnswerInputs.map((input) => ({
                                ...input,
                                user_id: fields.healthiePatientId,
                            })),
                        },
                    },
                    form_answer_group: {
                        id: true,
                    },
                },
            });
            const formAnswerGroupId = (_b = (_a = res === null || res === void 0 ? void 0 : res.createFormAnswerGroup) === null || _a === void 0 ? void 0 : _a.form_answer_group) === null || _b === void 0 ? void 0 : _b.id;
            if ((0, lodash_1.isEmpty)(formAnswerGroupId))
                throw new errors_1.HealthieFormResponseNotCreated(res);
            // separate call to lock the form if needed
            if (lock && formAnswerGroupId !== undefined) {
                await healthieSdk.client.mutation({
                    lockFormAnswerGroup: {
                        __args: {
                            input: {
                                id: formAnswerGroupId,
                            },
                        },
                        form_answer_group: {
                            id: true,
                        },
                    },
                });
            }
            await onComplete({
                data_points: {
                    formAnswerGroupId: String(formAnswerGroupId),
                },
                events: (0, logs_1.getSubActivityLogs)(omittedFormAnswers),
            });
        }
        catch (error) {
            if (error instanceof errors_2.HealthieError) {
                const errors = (0, errors_2.mapHealthieToActivityError)(error.errors);
                await onError({
                    events: [...errors, ...(0, logs_1.getSubActivityLogs)(omittedFormAnswers)],
                });
            }
            else if (error instanceof errors_1.HealthieFormResponseNotCreated) {
                await onError({
                    events: [
                        (0, errors_1.parseHealthieFormResponseNotCreatedError)(error.errors),
                        ...(0, logs_1.getSubActivityLogs)(omittedFormAnswers),
                    ],
                });
            }
            else {
                throw error;
            }
        }
    },
};
//# sourceMappingURL=pushFormResponseToHealthie.js.map