"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.startHostedPagesSession = 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");
const delay = async (ms) => {
    await new Promise((resolve) => setTimeout(resolve, ms));
};
exports.startHostedPagesSession = {
    key: 'startHostedPagesSession',
    category: extensions_core_1.Category.WORKFLOW,
    title: 'Start Hosted Pages Session',
    description: 'Start a new Hosted Pages session for a given stakeholder',
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: false,
    supports_automated_retries: true,
    onEvent: async ({ payload, onComplete, onError, helpers }) => {
        var _a;
        const { fields: { careFlowId, stakeholder }, } = (0, extensions_core_1.validate)({
            schema: zod_1.z.object({
                fields: config_1.FieldsValidationSchema,
            }),
            payload,
        });
        // To make sure the care flow activated the activity for the stakeholder :-)
        await delay(4000);
        const normalizedStakeholder = stakeholder.toLowerCase();
        const sdk = await helpers.awellSdk();
        const pathwayRes = await sdk.orchestration.query({
            pathway: {
                __args: {
                    id: careFlowId,
                },
                pathway: {
                    release_id: true,
                },
            },
        });
        const releaseId = (_a = pathwayRes === null || pathwayRes === void 0 ? void 0 : pathwayRes.pathway.pathway) === null || _a === void 0 ? void 0 : _a.release_id;
        if (releaseId === undefined)
            throw new Error('Could not retrieve the release ID for this care flow.');
        const getStakeholderId = async (releaseId) => {
            var _a;
            const stakeholdersInRelease = await sdk.orchestration.query({
                stakeholdersByReleaseIds: {
                    __args: {
                        release_ids: [releaseId],
                    },
                    success: true,
                    stakeholders: {
                        id: true,
                        label: {
                            en: true,
                        },
                        definition_id: true,
                    },
                },
            });
            helpers.log(stakeholdersInRelease, 'stakeholdersInRelease');
            const stakeholderMatchId = (_a = stakeholdersInRelease.stakeholdersByReleaseIds.stakeholders.find((stakeholder) => stakeholder.label.en.toLowerCase() === normalizedStakeholder)) === null || _a === void 0 ? void 0 : _a.id;
            if (stakeholderMatchId === undefined)
                throw new Error(`Could not find stakeholder ID for ${normalizedStakeholder} in care flow ${careFlowId}`);
            return stakeholderMatchId;
        };
        const stakeholderId = await getStakeholderId(releaseId);
        const res = await sdk.orchestration.mutation({
            startHostedActivitySession: {
                __args: {
                    input: {
                        pathway_id: careFlowId,
                        stakeholder_id: stakeholderId,
                    },
                },
                success: true,
                session_url: true,
            },
        });
        await onComplete({
            data_points: {
                sessionUrl: res.startHostedActivitySession.session_url,
            },
            events: [
                (0, addEventLog_1.addActivityEventLog)({
                    message: `Session started for care flow instance id ${careFlowId} and stakeholder ${stakeholder} (${stakeholderId}). Session URL is ${res.startHostedActivitySession.session_url}.`,
                }),
            ],
        });
    },
};
//# sourceMappingURL=startHostedPagesSession.js.map