"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pushFormResponsesToHealthie = 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 shared_1 = require("../shared");
const errors_1 = require("../../../lib/sdk/graphql-codegen/errors");
exports.pushFormResponsesToHealthie = {
    key: 'pushFormResponsesToHealthie',
    category: extensions_core_1.Category.DEMO,
    title: 'Push form responses to Healthie',
    description: 'Pushes all form response from the current step 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 an array of all form definitions and responses
         * in the current step at the time the current activity in that step is activated.
         */
        const formsData = await (0, awell_1.getAllFormsInCurrentStep)({
            awellSdk,
            pathwayId: pathway.id,
            activityId: activity.id,
        });
        const formDataWithHealthieFormAnswers = formsData.map((formData) => {
            const { formAnswers: healthieFormAnswerInputs, omittedFormAnswers } = awellSdk.utils.healthie.awellFormResponseToHealthieFormAnswers({
                awellFormDefinition: formData.formDefinition,
                awellFormResponse: formData.formResponse,
            });
            return {
                ...formData,
                healthieFormAnswerInputs,
                omittedFormAnswers,
            };
        });
        const mergedHealthieFormAnswers = formDataWithHealthieFormAnswers.flatMap(({ healthieFormAnswerInputs }) => healthieFormAnswerInputs);
        const mergedOmittedFormAnswers = formDataWithHealthieFormAnswers.flatMap(({ omittedFormAnswers }) => omittedFormAnswers);
        // indicates whether to make form values editable in Healthie
        const lock = (0, lodash_1.defaultTo)(fields.lockFormAnswerGroup, false);
        /**
         * Temporary log event to see the form answers we post to Healthie
         * Added because it helps Paloma with debugging why the form answers are not being posted
         * and unfortunately the Healthie API does not provide any useful error messages
         */
        const healthieFormAnswersLog = (0, awell_1.addActivityEventLog)({
            message: `Form answers:\n${JSON.stringify(mergedHealthieFormAnswers, null, 2)}`,
        });
        try {
            const res = await healthieSdk.client.mutation({
                createFormAnswerGroup: {
                    __args: {
                        input: {
                            finished: true,
                            custom_module_form_id: fields.healthieFormId,
                            user_id: fields.healthiePatientId,
                            form_answers: mergedHealthieFormAnswers.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 shared_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)(mergedOmittedFormAnswers),
            });
        }
        catch (error) {
            if (error instanceof errors_1.HealthieError) {
                const errors = (0, errors_1.mapHealthieToActivityError)(error.errors);
                await onError({
                    events: [
                        ...errors,
                        ...(0, logs_1.getSubActivityLogs)(mergedOmittedFormAnswers),
                        healthieFormAnswersLog,
                    ],
                });
                return;
            }
            if (error instanceof shared_1.HealthieFormResponseNotCreated) {
                await onError({
                    events: [
                        (0, shared_1.parseHealthieFormResponseNotCreatedError)(error.errors),
                        ...(0, logs_1.getSubActivityLogs)(mergedOmittedFormAnswers),
                        healthieFormAnswersLog,
                    ],
                });
                return;
            }
            const err = error;
            await onError({
                events: [
                    (0, awell_1.addActivityEventLog)({
                        message: `Error: ${err.message}`,
                    }),
                    healthieFormAnswersLog,
                ],
            });
        }
    },
};
//# sourceMappingURL=pushFormResponsesToHealthie.js.map