"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createReferralOrder = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const client_1 = require("../../client");
const config_1 = require("./config");
const axios_1 = require("axios");
/**
 * Important to know as the documentation is out of date:
 * - The specialty has to refer to an existing specialty in Elation. I can't find documentation on how to get
 * the list of specialties which means there is no way for us to validate that the field is OK.
 * - The send to contact field is required when creating a letter but again, not documented so unclear how to set it properly.
 */
exports.createReferralOrder = {
    key: 'createReferralOrder',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Create referral order',
    description: 'Create a referral order in Elation.',
    fields: config_1.fields,
    previewable: true,
    dataPoints: config_1.dataPoints,
    onActivityCreated: async (payload, onComplete, onError) => {
        var _a, _b, _c;
        try {
            const { patient, practice, contact_name, body, authorization_for, consultant_name, specialty, } = config_1.FieldsValidationSchema.parse(payload.fields);
            const api = (0, client_1.makeAPIClient)(payload.settings);
            const contactsResponse = await api.searchContactsByName({
                name: contact_name,
            });
            if (contactsResponse.count === 0) {
                throw new Error(`No contact found with the name ${contact_name}.`);
            }
            const contact = contactsResponse.results[0];
            const referralOrderResponse = await api.createReferralOrder({
                authorization_for,
                consultant_name,
                short_consultant_name: consultant_name,
                practice,
                patient,
                specialty: { name: specialty },
                // Setting these to null as we don't know whether they are useful or not.
                // If needed we can add them to the action fields.
                auth_number: null,
                date_for_reEval: null,
                resolution: null,
            });
            await api.postNewLetter({
                patient,
                practice,
                body,
                referral_order: referralOrderResponse.id,
                send_to_contact: { id: contact.id },
                letter_type: 'referral',
            });
            await onComplete({
                data_points: {
                    id: String(referralOrderResponse.id),
                },
            });
        }
        catch (err) {
            if (err instanceof axios_1.AxiosError) {
                const responseData = (_a = err.response) === null || _a === void 0 ? void 0 : _a.data;
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: {
                                en: `${(_b = err.status) !== null && _b !== void 0 ? _b : '(no status code)'} Error: ${err.message}`,
                            },
                            error: {
                                category: 'SERVER_ERROR',
                                message: `${(_c = err.status) !== null && _c !== void 0 ? _c : '(no status code)'} Error data: ${JSON.stringify(responseData, null, 2)}`,
                            },
                        },
                    ],
                });
            }
            else {
                throw err;
            }
        }
    },
};
//# sourceMappingURL=createReferralOrder.js.map