"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPatient = 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.getPatient = {
    key: 'getPatient',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Get patient',
    description: 'Retrieve patient details from Epic',
    fields: config_1.fields,
    previewable: false,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError }) => {
        var _a, _b;
        const { epicFhirR4Sdk, fields: { resourceId }, } = await (0, validatePayloadAndCreateSdks_1.validatePayloadAndCreateSdks)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        try {
            const res = await epicFhirR4Sdk.getPatient(resourceId);
            const humanName = (_a = res.data.name) === null || _a === void 0 ? void 0 : _a.find((name) => name.use === 'official');
            const officialGivenName = (_b = humanName === null || humanName === void 0 ? void 0 : humanName.given) === null || _b === void 0 ? void 0 : _b[0];
            const officialFamilyName = humanName === null || humanName === void 0 ? void 0 : humanName.family;
            const birthDate = res.data.birthDate;
            await onComplete({
                data_points: {
                    patient: JSON.stringify(res.data),
                    officialGivenName,
                    officialFamilyName,
                    birthDate,
                },
            });
        }
        catch (error) {
            if (error instanceof axios_1.AxiosError) {
                const err = error;
                if (err.status === 404)
                    await onError({
                        events: [
                            (0, awell_1.addActivityEventLog)({
                                message: 'Patient not found',
                            }),
                        ],
                    });
                return;
            }
            // Throw all other errors
            throw error;
        }
    },
};
//# sourceMappingURL=getPatient.js.map