"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.observationCreated = void 0;
const lodash_1 = require("lodash");
const constants_1 = require("../../constants");
const dataPoints = {
    observation: {
        key: 'observation',
        valueType: 'json',
    },
    observationId: {
        key: 'observationId',
        valueType: 'string',
    },
};
exports.observationCreated = {
    key: 'observationCreated',
    dataPoints,
    onEvent: async ({ payload: { payload, rawBody, headers, settings }, onSuccess, onError, }) => {
        var _a, _b, _c, _d;
        const observation = payload;
        const subject = observation === null || observation === void 0 ? void 0 : observation.subject;
        const isPatientSubject = (_b = (_a = subject === null || subject === void 0 ? void 0 : subject.reference) === null || _a === void 0 ? void 0 : _a.startsWith('Patient/')) !== null && _b !== void 0 ? _b : false;
        /**
         * Observations not attached to a patient don't make much sense to us.
         * So I'm discarding them.
         */
        if ((0, lodash_1.isNil)(subject) || !isPatientSubject) {
            await onError({
                response: {
                    statusCode: 400,
                    message: 'Missing patient subject reference in Observation payload. Only observations attached to a patient are processed.',
                },
            });
            return;
        }
        const subjectAsPatient = subject;
        const patientId = (_c = subjectAsPatient.reference) === null || _c === void 0 ? void 0 : _c.split('/')[1];
        await onSuccess({
            data_points: {
                observation: JSON.stringify(observation),
                observationId: (_d = observation.id) !== null && _d !== void 0 ? _d : '',
            },
            ...(!(0, lodash_1.isNil)(patientId) && {
                patient_identifier: {
                    system: constants_1.MEDPLUM_IDENTIFIER,
                    value: patientId,
                },
            }),
        });
    },
};
//# sourceMappingURL=ObservationCreated.js.map