"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");
const getResourceId_1 = require("../../lib/api/getResourceId");
exports.createPatient = {
    key: 'createPatient',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Create patient',
    description: 'Create a patient in Cerner',
    fields: config_1.fields,
    previewable: true,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError }) => {
        var _a, _b, _c, _d;
        const { cernerFhirR4Sdk, fields: { familyName, givenName, email, gender, birthDate, ssn, assigningOrganizationId, }, } = await (0, validatePayloadAndCreateSdks_1.validatePayloadAndCreateSdks)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        const PatientResource = {
            resourceType: 'Patient',
            identifier: [
                // Assigning Organization ID (required)
                {
                    assigner: {
                        reference: `Organization/${assigningOrganizationId}`,
                    },
                },
                // Social Security Number
                ...(!(0, lodash_1.isEmpty)(ssn)
                    ? [
                        {
                            type: {
                                coding: [
                                    {
                                        system: 'http://terminology.hl7.org/CodeSystem/v2-0203',
                                        code: 'SS',
                                    },
                                ],
                            },
                            system: 'http://hl7.org/fhir/sid/us-ssn',
                            value: ssn,
                        },
                    ]
                    : []),
            ],
            name: [
                {
                    use: 'official',
                    family: familyName,
                    given: [givenName],
                },
            ],
            ...(!(0, lodash_1.isEmpty)(gender) && {
                gender,
            }),
            ...(!(0, lodash_1.isEmpty)(birthDate) && {
                birthDate: birthDate.toISOString().split('T')[0],
            }),
            ...(!(0, lodash_1.isEmpty)(email) && {
                telecom: [
                    {
                        use: 'home',
                        system: 'email',
                        value: email,
                    },
                ],
            }),
        };
        try {
            const res = await cernerFhirR4Sdk.createPatient(PatientResource);
            const resourceReference = (_a = res.headers.Location) !== null && _a !== void 0 ? _a : res.headers.location;
            const resourceId = (0, getResourceId_1.getResourceId)(resourceReference);
            await onComplete({
                data_points: {
                    resourceId,
                },
            });
        }
        catch (error) {
            if (error instanceof axios_1.AxiosError) {
                const err = error;
                await onError({
                    events: [
                        (0, awell_1.addActivityEventLog)({
                            message: `Status: ${String((_b = err.response) === null || _b === void 0 ? void 0 : _b.status)} (${String((_c = err.response) === null || _c === void 0 ? void 0 : _c.statusText)})\n${JSON.stringify((_d = err.response) === null || _d === void 0 ? void 0 : _d.data, null, 2)}`,
                        }),
                    ],
                });
                return;
            }
            // Throw all other errors
            throw error;
        }
    },
};
//# sourceMappingURL=createPatient.js.map