"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDocument = 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 awell_1 = require("../../../../src/lib/awell");
const getResourceId_1 = require("../../lib/api/getResourceId");
exports.createDocument = {
    key: 'createDocument',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Create document',
    description: 'Create a document in Cerner',
    fields: config_1.fields,
    previewable: false,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError }) => {
        var _a, _b, _c, _d;
        const { cernerFhirR4Sdk, fields: { patientResourceId, encounterResourceId, type, note }, } = await (0, validatePayloadAndCreateSdks_1.validatePayloadAndCreateSdks)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        const DocumentReferenceInput = {
            resourceType: 'DocumentReference',
            status: 'current',
            docStatus: 'final',
            type: {
                // Hardcoding the type to Progress Note for now
                coding: [
                    {
                        system: 'http://loinc.org',
                        code: '11506-3',
                        userSelected: false,
                    },
                ],
                text: type,
            },
            subject: {
                reference: `Patient/${patientResourceId}`,
            },
            content: [
                {
                    attachment: {
                        contentType: 'text/plain;charset=utf-8',
                        data: Buffer.from(note, 'utf-8').toString('base64'),
                    },
                },
            ],
            context: {
                encounter: [
                    {
                        reference: `Encounter/${encounterResourceId}`,
                    },
                ],
                // Required
                period: {
                    start: new Date().toISOString(),
                    end: new Date().toISOString(),
                },
            },
        };
        try {
            const res = await cernerFhirR4Sdk.createDocumentReference(DocumentReferenceInput);
            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=createDocument.js.map