"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAppointment = 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.getAppointment = {
    key: 'getAppointment',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Get appointment',
    description: 'Retrieve appointment details from Cerner',
    fields: config_1.fields,
    previewable: true,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError }) => {
        var _a, _b, _c, _d, _e, _f;
        const { cernerFhirR4Sdk, fields: { resourceId }, } = await (0, validatePayloadAndCreateSdks_1.validatePayloadAndCreateSdks)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        try {
            const res = await cernerFhirR4Sdk.getAppointment(resourceId);
            const patient = res.data.participant.find((participant) => { var _a, _b; return (_b = (_a = participant.actor) === null || _a === void 0 ? void 0 : _a.reference) === null || _b === void 0 ? void 0 : _b.startsWith('Patient'); });
            const patientId = (_b = (_a = patient === null || patient === void 0 ? void 0 : patient.actor) === null || _a === void 0 ? void 0 : _a.reference) === null || _b === void 0 ? void 0 : _b.split('/')[1];
            await onComplete({
                data_points: {
                    appointment: JSON.stringify(res.data),
                    patientId,
                    appointmentStatus: res.data.status,
                    appointmentStartDateTime: res.data.start,
                    appointmentTypeCode: (_f = (_e = (_d = (_c = res.data) === null || _c === void 0 ? void 0 : _c.appointmentType) === null || _d === void 0 ? void 0 : _d.coding) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.code,
                },
            });
        }
        catch (error) {
            if (error instanceof axios_1.AxiosError) {
                const err = error;
                if (err.status === 404)
                    await onError({
                        events: [
                            (0, awell_1.addActivityEventLog)({
                                message: 'Appointment not found',
                            }),
                        ],
                    });
                return;
            }
            // Throw all other errors
            throw error;
        }
    },
};
//# sourceMappingURL=getAppointment.js.map