"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.findPatientByMRN = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const validatePayloadAndCreateSdks_1 = require("../../lib/validatePayloadAndCreateSdks");
const axios_1 = require("axios");
const awell_1 = require("../../../../src/lib/awell");
exports.findPatientByMRN = {
    key: 'findPatientByMRN',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Find patient by MRN',
    description: 'Find patient by MRN in Cerner',
    fields: config_1.fields,
    previewable: true,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError }) => {
        var _a, _b, _c, _d, _e, _f, _g;
        const { cernerFhirR4Sdk, fields: { MRN }, } = await (0, validatePayloadAndCreateSdks_1.validatePayloadAndCreateSdks)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        try {
            const { data } = await cernerFhirR4Sdk.searchPatient({ MRN });
            const matchCount = (_a = data.total) !== null && _a !== void 0 ? _a : 0;
            if (matchCount === 0) {
                throw new Error('No patient found');
            }
            if (matchCount > 1) {
                throw new Error('Multiple patients found');
            }
            await onComplete({
                data_points: {
                    resourceId: (_d = (_c = (_b = data === null || data === void 0 ? void 0 : data.entry) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.resource) === null || _d === void 0 ? void 0 : _d.id,
                },
            });
        }
        catch (error) {
            if (error instanceof axios_1.AxiosError) {
                const err = error;
                await onError({
                    events: [
                        (0, awell_1.addActivityEventLog)({
                            message: `Status: ${String((_e = err.response) === null || _e === void 0 ? void 0 : _e.status)} (${String((_f = err.response) === null || _f === void 0 ? void 0 : _f.statusText)})\n${JSON.stringify((_g = err.response) === null || _g === void 0 ? void 0 : _g.data, null, 2)}`,
                        }),
                    ],
                });
                return;
            }
            // Throw all other errors
            throw error;
        }
    },
};
//# sourceMappingURL=findPatientByMRN.js.map