"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.matchPatient = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const validatePayloadAndCreateSdks_1 = require("../../lib/validatePayloadAndCreateSdks");
const lodash_1 = require("lodash");
const axios_1 = require("axios");
const awell_1 = require("../../../../src/lib/awell");
exports.matchPatient = {
    key: 'matchPatient',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Match patient',
    description: 'Match patient to existing patient in Epic',
    fields: config_1.fields,
    previewable: false,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError }) => {
        var _a;
        const { epicFhirR4Sdk, fields: { familyName, givenName, birthDate, gender, email }, } = await (0, validatePayloadAndCreateSdks_1.validatePayloadAndCreateSdks)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        /**
         * Matching by SSN is not allowed due to security reasons.
         */
        const patientMatchInput = {
            resourceType: 'Parameters',
            parameter: [
                {
                    name: 'resource',
                    resource: {
                        resourceType: 'Patient',
                        name: [
                            {
                                family: familyName,
                                given: [givenName],
                            },
                        ],
                        birthDate: birthDate.toISOString().split('T')[0],
                        gender,
                        ...(!(0, lodash_1.isEmpty)(email) && {
                            telecom: [
                                {
                                    system: 'email',
                                    value: email,
                                },
                            ],
                        }),
                    },
                },
                {
                    name: 'onlyCertainMatches',
                    valueBoolean: 'true',
                },
            ],
        };
        try {
            const { data } = await epicFhirR4Sdk.matchPatient(patientMatchInput);
            const matchCount = data.total;
            if (matchCount !== 1) {
                throw new Error('No match found');
            }
            await onComplete({
                data_points: {
                    resourceId: data.entry[0].resource.id,
                },
            });
        }
        catch (error) {
            if (error instanceof axios_1.AxiosError) {
                const err = error;
                await onError({
                    events: [
                        (0, awell_1.addActivityEventLog)({
                            message: JSON.stringify((_a = err.response) === null || _a === void 0 ? void 0 : _a.data, null, 2),
                        }),
                    ],
                });
                return;
            }
            // Throw all other errors
            throw error;
        }
    },
};
//# sourceMappingURL=matchPatient.js.map