"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.submitQuestionnaireResponse = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const utils_1 = require("../../utils");
const extractResourceId_1 = require("../../utils/extractResourceId/extractResourceId");
const awell_1 = require("../../../../src/lib/awell");
exports.submitQuestionnaireResponse = {
    key: 'submitQuestionnaireResponse',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Submit questionnaire response',
    description: 'Creates a questionnaire response in Medplum for the latest submitted form in the current step',
    fields: config_1.fields,
    previewable: false,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError, helpers }) => {
        var _a;
        const { fields: input, medplumSdk, pathway, activity, } = await (0, utils_1.validateAndCreateSdkClient)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        const awellSdk = await helpers.awellSdk();
        let formDefinition;
        let formResponse;
        try {
            const formRes = await (0, awell_1.getLatestFormInCurrentStep)({
                awellSdk,
                pathwayId: pathway.id,
                activityId: activity.id,
            });
            helpers.log(formRes, 'Form response');
            formDefinition = formRes.formDefinition;
            formResponse = formRes.formResponse;
        }
        catch (error) {
            helpers.log({ error }, 'Error');
            const err = error;
            await onError({
                events: [(0, awell_1.addActivityEventLog)({ message: err.message })],
            });
            return;
        }
        helpers.log({ formDefinition, formResponse }, 'Form definition and response');
        const FhirQuestionnaire = awellSdk.utils.fhir.AwellFormToFhirQuestionnaire(formDefinition);
        const FhirQuestionnaireResponse = awellSdk.utils.fhir.AwellFormResponseToFhirQuestionnaireResponseItems({
            awellFormDefinition: formDefinition,
            awellFormResponse: formResponse,
        });
        helpers.log({ FhirQuestionnaire, FhirQuestionnaireResponse }, 'Fhir questionnaire and response');
        const QuestionnaireResource = await medplumSdk.createResourceIfNoneExist(FhirQuestionnaire, `identifier=${formDefinition.definition_id}/published/${formDefinition.id}`);
        helpers.log({ QuestionnaireResource }, 'Questionnaire resource');
        const res = await medplumSdk.createResource({
            resourceType: 'QuestionnaireResponse',
            questionnaire: `Questionnaire/${String(QuestionnaireResource.id)}`,
            status: 'completed',
            subject: {
                reference: `Patient/${(_a = (0, extractResourceId_1.extractResourceId)(input.patientId, 'Patient')) !== null && _a !== void 0 ? _a : 'undefined'}`,
            },
            item: FhirQuestionnaireResponse,
        });
        helpers.log({ res }, 'Questionnaire response');
        await onComplete({
            data_points: {
                // @ts-expect-error id is not included in the response type?
                questionnnaireResponseId: res.id,
            },
        });
    },
};
//# sourceMappingURL=submitQuestionnaireResponse.js.map