"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNaviSession = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const zod_1 = require("zod");
const addEventLog_1 = require("../../../../../src/lib/awell/addEventLog");
exports.createNaviSession = {
    key: 'createNaviSession',
    category: extensions_core_1.Category.WORKFLOW,
    title: 'Create Navi Session',
    description: 'Create a Navi portal session for a stakeholder',
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: false,
    supports_automated_retries: true,
    onEvent: async ({ payload, onComplete, onError }) => {
        var _a, _b, _c;
        const { fields: { stakeholderId, exp }, } = (0, extensions_core_1.validate)({
            schema: zod_1.z.object({
                fields: config_1.FieldsValidationSchema,
            }),
            payload,
        });
        const careflowId = payload.pathway.id;
        const orgId = payload.pathway.org_id;
        const tenantId = payload.pathway.tenant_id;
        const environment = (_a = process.env.AWELL_ENVIRONMENT) !== null && _a !== void 0 ? _a : 'test';
        const body = {
            orgId,
            tenantId,
            environment,
            exp: exp !== null && exp !== void 0 ? exp : Math.floor(Date.now() / 1000) + 3600 * 24 * 30,
            patientId: payload.patient.id,
            stakeholderId: stakeholderId !== null && stakeholderId !== void 0 ? stakeholderId : payload.patient.id,
            careflowId,
        };
        try {
            const response = await fetch('https://navi-portal.awellhealth.com/api/session/create', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(body),
            });
            const ResponseSchema = zod_1.z.union([
                zod_1.z.object({ session_id: zod_1.z.string() }),
                zod_1.z.object({ error: zod_1.z.string() }),
            ]);
            const json = ResponseSchema.parse(await response.json());
            if (!response.ok || 'error' in json) {
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: {
                                en: `Failed to create Navi session: ${response.status} ${response.statusText} ${'error' in json ? json.error : ''}`,
                            },
                            error: {
                                category: 'SERVER_ERROR',
                                message: `Failed to create Navi session: ${response.status} ${response.statusText}`,
                            },
                        },
                    ],
                });
                return;
            }
            const sessionId = json.session_id;
            if (sessionId == null) {
                await onError({
                    events: [
                        {
                            date: new Date().toISOString(),
                            text: {
                                en: 'Failed to create Navi session: missing session id in response',
                            },
                            error: {
                                category: 'SERVER_ERROR',
                                message: 'Failed to create Navi session: missing session id in response',
                            },
                        },
                    ],
                });
                return;
            }
            await onComplete({
                data_points: {
                    sessionId,
                    statusCode: String(response.status),
                    naviSessionUrl: `https://navi-portal.awellhealth.com/direct/${sessionId}`,
                },
                events: [
                    (0, addEventLog_1.addActivityEventLog)({
                        message: `Created Navi session for care flow ${careflowId} (stakeholder: ${stakeholderId !== null && stakeholderId !== void 0 ? stakeholderId : 'patient'})`,
                    }),
                ],
            });
        }
        catch (error) {
            const err = error;
            await onError({
                events: [
                    {
                        date: new Date().toISOString(),
                        text: {
                            en: (_b = err.message) !== null && _b !== void 0 ? _b : 'Unexpected error while creating Navi session',
                        },
                        error: {
                            category: 'SERVER_ERROR',
                            message: (_c = err.message) !== null && _c !== void 0 ? _c : 'Unexpected error while creating Navi session',
                        },
                    },
                ],
            });
        }
    },
};
//# sourceMappingURL=createNaviSession.js.map