"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPatientEncounters = 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.getPatientEncounters = {
    key: 'getPatientEncounters',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Get patient encounters',
    description: 'Retrieve all encounters for a patient',
    fields: config_1.fields,
    previewable: true,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError }) => {
        var _a, _b, _c;
        const { cernerFhirR4Sdk, fields: { patientResourceId }, } = await (0, validatePayloadAndCreateSdks_1.validatePayloadAndCreateSdks)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        try {
            const { data } = await cernerFhirR4Sdk.searchEncounter({
                patientResourceId,
            });
            if ((data === null || data === void 0 ? void 0 : data.total) === 0) {
                throw new Error('No encounters found');
            }
            await onComplete({
                data_points: {
                    encounters: JSON.stringify(data.entry),
                },
            });
        }
        catch (error) {
            if (error instanceof axios_1.AxiosError) {
                const err = error;
                await onError({
                    events: [
                        (0, awell_1.addActivityEventLog)({
                            message: `Status: ${String((_a = err.response) === null || _a === void 0 ? void 0 : _a.status)} (${String((_b = err.response) === null || _b === void 0 ? void 0 : _b.statusText)})\n${JSON.stringify((_c = err.response) === null || _c === void 0 ? void 0 : _c.data, null, 2)}`,
                        }),
                    ],
                });
                return;
            }
            // Throw all other errors
            throw error;
        }
    },
};
//# sourceMappingURL=getPatientEncounters.js.map