"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createCalculationObservation = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const utils_1 = require("../../utils");
const lodash_1 = require("lodash");
const extractResourceId_1 = require("../../utils/extractResourceId/extractResourceId");
const awell_1 = require("../../../../src/lib/awell");
exports.createCalculationObservation = {
    key: 'createCalculationObservation',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Create calculation observation',
    description: 'Create a calculation observation in Medplum',
    fields: config_1.fields,
    previewable: false,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError, helpers }) => {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j;
        const { fields: input, medplumSdk, pathway, activity, } = await (0, utils_1.validateAndCreateSdkClient)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        const awellSdk = await helpers.awellSdk();
        let latestCalculationActivity;
        try {
            const res = await (0, awell_1.getLastCalculationActivityInCurrentStep)({
                awellSdk,
                pathwayId: pathway.id,
                currentActivityId: activity.id,
            });
            if ((0, lodash_1.isNil)(res)) {
                throw new Error('No calculation activity found in the current step');
            }
            latestCalculationActivity = res;
        }
        catch (error) {
            const err = error;
            await onError({
                events: [
                    (0, awell_1.addActivityEventLog)({
                        message: err.message,
                    }),
                ],
            });
            return;
        }
        const calculationResultsResponse = await awellSdk.orchestration.query({
            calculationResults: {
                __args: {
                    pathway_id: pathway.id,
                    activity_id: latestCalculationActivity.id,
                },
                success: true,
                result: {
                    __scalar: true,
                },
            },
        });
        const derivedFrom = !(0, lodash_1.isEmpty)(input.questionnaireResponseId)
            ? {
                reference: `QuestionnaireResponse/${(_b = (0, extractResourceId_1.extractResourceId)((_a = input.questionnaireResponseId) !== null && _a !== void 0 ? _a : '', 'QuestionnaireResponse')) !== null && _b !== void 0 ? _b : 'undefined'}`,
            }
            : null;
        /**
         * We currently only support one result per calculation activity so
         * we use an imperfect heuristic to just get the first result of the calculation
         */
        const score = (_d = (_c = calculationResultsResponse.calculationResults) === null || _c === void 0 ? void 0 : _c.result[0]) === null || _d === void 0 ? void 0 : _d.value;
        const isValidScore = !(0, lodash_1.isNil)(score) && !isNaN(Number(score)) && !(0, lodash_1.isEmpty)(score);
        const scoreResult = isValidScore
            ? { valueQuantity: { value: Number(score) } }
            : {
                dataAbsentReason: {
                    coding: [
                        {
                            system: 'http://hl7.org/fhir/data-absent-reason',
                            code: 'not-performed',
                            display: 'Not Performed',
                        },
                    ],
                },
            };
        const res = await medplumSdk.createResource({
            resourceType: 'Observation',
            status: 'final',
            code: {
                text: (_f = (_e = latestCalculationActivity === null || latestCalculationActivity === void 0 ? void 0 : latestCalculationActivity.object) === null || _e === void 0 ? void 0 : _e.name) !== null && _f !== void 0 ? _f : 'Unknown',
            },
            category: [
                {
                    coding: [
                        {
                            system: 'http://terminology.hl7.org/CodeSystem/observation-category',
                            code: 'survey',
                            display: 'Survey',
                        },
                    ],
                    text: (_h = (_g = latestCalculationActivity === null || latestCalculationActivity === void 0 ? void 0 : latestCalculationActivity.object) === null || _g === void 0 ? void 0 : _g.name) !== null && _h !== void 0 ? _h : 'Unknown',
                },
            ],
            subject: {
                reference: `Patient/${(_j = (0, extractResourceId_1.extractResourceId)(input.patientId, 'Patient')) !== null && _j !== void 0 ? _j : 'undefined'}`,
            },
            performer: [
                {
                    identifier: {
                        system: 'https://awellhealth.com/activities/',
                        value: activity.id,
                    },
                    display: 'Awell',
                },
            ],
            derivedFrom: [...(derivedFrom != null ? [derivedFrom] : [])],
            ...scoreResult,
        });
        await onComplete({
            data_points: {
                // @ts-expect-error should be fine
                observationId: res === null || res === void 0 ? void 0 : res.id,
            },
        });
    },
};
//# sourceMappingURL=createCalculationObservation.js.map