"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPatient = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const client_1 = require("../../client");
const patient_zod_1 = require("../../validation/patient.zod");
const lodash_1 = require("lodash");
const config_1 = require("./config");
const axios_1 = require("axios");
const addEventLog_1 = require("../../../../src/lib/awell/addEventLog");
exports.createPatient = {
    key: 'createPatient',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Create Patient',
    description: "Create a patient profile using Elation's patient API.",
    fields: config_1.fields,
    previewable: true,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError }) => {
        var _a, _b, _c;
        const { firstName, lastName, actualName, caregiverPracticeId, genderIdentity, legalGenderMarker, middleName, preferredLanguage, previousFirstName, previousLastName, primaryPhysicianId, sexualOrientation, dob, sex, email, mobilePhone, pronouns, ssn, ethnicity, race, notes, tags, } = config_1.FieldsValidationSchema.parse(payload.fields);
        const api = (0, client_1.makeAPIClient)(payload.settings);
        const patientEmail = (0, lodash_1.isNil)(email) || (0, lodash_1.isEmpty)(email) ? undefined : [{ email }];
        const patientMobilePhone = (0, lodash_1.isNil)(mobilePhone) || (0, lodash_1.isEmpty)(mobilePhone)
            ? undefined
            : [{ phone: mobilePhone, phone_type: 'Mobile' }];
        const patient = patient_zod_1.patientSchema.parse({
            first_name: firstName,
            last_name: lastName,
            primary_physician: primaryPhysicianId,
            caregiver_practice: caregiverPracticeId,
            middle_name: middleName,
            actual_name: actualName,
            gender_identity: genderIdentity,
            legal_gender_marker: legalGenderMarker,
            sexual_orientation: sexualOrientation,
            preferred_language: preferredLanguage,
            previous_first_name: previousFirstName,
            previous_last_name: previousLastName,
            emails: patientEmail,
            phones: patientMobilePhone,
            dob,
            sex,
            pronouns,
            ssn,
            ethnicity,
            race,
            notes,
            tags,
        });
        try {
            const { data } = await api.createPatient(patient);
            await onComplete({
                data_points: {
                    patientId: String(data.id),
                },
            });
        }
        catch (err) {
            // Handle the patient exists already specifically. Every other validation or axios error is handled
            // by the default error handler in extensions-core.
            if (err instanceof axios_1.AxiosError && ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 409) {
                await onComplete({
                    data_points: {
                        patientId: String((_c = (_b = err.response) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.redirect),
                    },
                    events: [
                        (0, addEventLog_1.addActivityEventLog)({
                            message: `Patient already exists. Returning the existing patient id.`,
                        }),
                    ],
                });
                return;
            }
            throw err;
        }
    },
};
//# sourceMappingURL=createPatient.js.map