"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPatient = 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 lodash_1 = require("lodash");
const awell_1 = require("../../../../src/lib/awell");
exports.createPatient = {
    key: 'createPatient',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Create patient',
    description: 'Create a patient in Epic',
    fields: config_1.fields,
    previewable: false,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError }) => {
        var _a, _b;
        const { epicFhirR4Sdk, fields: { familyName, givenName, email, gender, birthDate, ssn }, } = await (0, validatePayloadAndCreateSdks_1.validatePayloadAndCreateSdks)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        const PatientResource = {
            resourceType: 'Patient',
            identifier: [
                {
                    use: 'usual',
                    system: 'urn:oid:2.16.840.1.113883.4.1', // SSN
                    value: ssn,
                },
            ],
            name: [
                {
                    use: 'official',
                    family: familyName,
                    given: [givenName],
                },
            ],
            gender,
            birthDate: birthDate.toISOString().split('T')[0],
            ...(!(0, lodash_1.isEmpty)(email) && {
                telecom: [
                    {
                        system: 'email',
                        value: email,
                    },
                ],
            }),
        };
        try {
            const res = await epicFhirR4Sdk.createPatient(PatientResource);
            const resourceReference = (_a = res.headers.Location) !== null && _a !== void 0 ? _a : res.headers.location;
            const resourceId = resourceReference.split('/')[1];
            await onComplete({
                data_points: {
                    resourceId,
                },
            });
        }
        catch (error) {
            if (error instanceof axios_1.AxiosError) {
                const err = error;
                await onError({
                    events: [
                        (0, awell_1.addActivityEventLog)({
                            message: JSON.stringify((_b = err.response) === null || _b === void 0 ? void 0 : _b.data, null, 2),
                        }),
                    ],
                });
                return;
            }
            // Throw all other errors
            throw error;
        }
    },
};
//# sourceMappingURL=createPatient.js.map