"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.postLetter = void 0;
/* eslint-disable @typescript-eslint/naming-convention */
const zod_1 = require("zod");
const extensions_core_1 = require("@awell-health/extensions-core");
const client_1 = require("../client");
const zod_validation_error_1 = require("zod-validation-error");
const axios_1 = require("axios");
const letter_zod_1 = require("../validation/letter.zod");
const fields = {
    patientId: {
        id: 'patientId',
        label: 'Patient ID',
        description: 'ID of the patient',
        type: extensions_core_1.FieldType.NUMERIC,
        required: true,
    },
    practiceId: {
        id: 'practiceId',
        label: 'Practice',
        description: 'ID of a Practice',
        type: extensions_core_1.FieldType.NUMERIC,
        required: true,
    },
    referralOrderId: {
        id: 'referralOrderId',
        label: 'Referral Order ID',
        description: 'Id of the Referral Order (Not needed with subject)',
        type: extensions_core_1.FieldType.NUMERIC,
        required: false,
    },
    subject: {
        id: 'subject',
        label: 'Subject',
        description: 'Subject of the letter (Not needed with referral order)',
        type: extensions_core_1.FieldType.STRING,
        required: false,
    },
    body: {
        id: 'body',
        label: 'Body',
        description: 'Body of the letter',
        type: extensions_core_1.FieldType.TEXT,
        required: true,
    },
    contactNpi: {
        id: 'contactNpi',
        label: 'Contact NPI code',
        description: 'NPI of the contact whom you want to send this letter',
        type: extensions_core_1.FieldType.STRING,
        required: true,
    },
    letterType: {
        id: 'letterType',
        label: 'Type of letter',
        description: 'Type of letter. Defaults to "provider". The type can be one of the following: "patient", "referral", "provider" or "patient_initiated".',
        type: extensions_core_1.FieldType.STRING,
        required: false,
    },
};
const dataPoints = {
    letterId: {
        key: 'letterId',
        valueType: 'number',
    },
};
exports.postLetter = {
    key: 'postLetter',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Post letter',
    description: "Post a letter using Elation's patient API.",
    fields,
    previewable: true,
    dataPoints,
    onActivityCreated: async (payload, onComplete, onError) => {
        var _a, _b;
        try {
            const { patientId, practiceId, referralOrderId, subject, body, contactNpi, letterType, } = payload.fields;
            const contact_npi = zod_1.z.string().parse(contactNpi);
            const api = (0, client_1.makeAPIClient)(payload.settings);
            const findContactsResponse = await api.searchContactsByNpi({
                npi: contact_npi,
            });
            if (findContactsResponse.count === 0 ||
                findContactsResponse.results.length === 0) {
                throw new Error('No contact found with this NPI');
            }
            const contact = findContactsResponse.results[0];
            const letter = letter_zod_1.letterSchema.parse({
                patient: patientId,
                practice: practiceId,
                referral_order: referralOrderId,
                subject,
                body,
                letter_type: letterType,
                send_to_contact: {
                    id: contact.id,
                },
            });
            const { id } = await api.postNewLetter(letter);
            await onComplete({
                data_points: {
                    letterId: String(id),
                },
            });
        }
        catch (err) {
            if (err instanceof zod_1.ZodError) {
                const error = (0, zod_validation_error_1.fromZodError)(err);
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: { en: error.message },
                            error: {
                                category: 'WRONG_INPUT',
                                message: error.message,
                            },
                        },
                    ],
                });
            }
            else if (err instanceof axios_1.AxiosError) {
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: {
                                en: `${(_a = err.status) !== null && _a !== void 0 ? _a : '(no status code)'} Error: ${err.message}`,
                            },
                            error: {
                                category: 'SERVER_ERROR',
                                message: `${(_b = err.status) !== null && _b !== void 0 ? _b : '(no status code)'} Error: ${err.message}`,
                            },
                        },
                    ],
                });
            }
            else {
                const message = err.message;
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: { en: message },
                            error: {
                                category: 'SERVER_ERROR',
                                message,
                            },
                        },
                    ],
                });
            }
        }
    },
};
//# sourceMappingURL=postLetter.js.map