"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAllFormsInCurrentStep = void 0;
const lodash_1 = require("lodash");
const logDebug = (log, message, data) => {
    log === null || log === void 0 ? void 0 : log(data, `[getAllFormsInCurrentStep] ${message}`);
};
const getAllFormsInCurrentStep = async ({ awellSdk, pathwayId, activityId, log, }) => {
    var _a, _b, _c;
    const activity_response = await awellSdk.orchestration
        .query({
        activity: {
            __args: {
                id: activityId,
            },
            success: true,
            activity: {
                id: true,
                status: true,
                date: true,
                object: {
                    id: true,
                    type: true,
                },
                context: {
                    step_id: true,
                },
            },
        },
    })
        .catch((error) => {
        logDebug(log, 'Failed to fetch activity', {
            activityId,
            pathwayId,
            error,
        });
        throw new Error(`Failed to fetch activity ${activityId}`);
    });
    const currentActivity = (_a = activity_response === null || activity_response === void 0 ? void 0 : activity_response.activity) === null || _a === void 0 ? void 0 : _a.activity;
    if ((0, lodash_1.isNil)(currentActivity) || !activity_response.activity.success) {
        logDebug(log, 'Activity query did not return a successful activity', {
            activityId,
            pathwayId,
            activityResponse: JSON.stringify(activity_response),
        });
        throw new Error(`Failed to fetch activity ${activityId}`);
    }
    logDebug(log, 'Fetched current activity', {
        activityId: currentActivity.id,
        status: currentActivity.status,
        date: currentActivity.date,
        objectId: currentActivity.object.id,
        objectType: currentActivity.object.type,
        stepId: (_b = currentActivity.context) === null || _b === void 0 ? void 0 : _b.step_id,
    });
    const currentStepId = (_c = currentActivity.context) === null || _c === void 0 ? void 0 : _c.step_id;
    if ((0, lodash_1.isNil)(currentStepId)) {
        logDebug(log, 'Could not find step ID of the current activity', {
            activityId,
            pathwayId,
            currentActivity: JSON.stringify(currentActivity),
        });
        throw new Error(`Could not find step ID of the current activity for activity ${activityId}`);
    }
    const activities = await awellSdk.orchestration.query({
        pathwayStepActivities: {
            __args: {
                pathway_id: pathwayId,
                step_id: currentStepId,
            },
            success: true,
            activities: {
                id: true,
                status: true,
                date: true,
                object: {
                    id: true,
                    type: true,
                },
                context: {
                    step_id: true,
                },
            },
        },
    });
    logDebug(log, 'Fetched pathway step activities', {
        activityId,
        pathwayId,
        stepId: currentStepId,
        totalActivities: activities.pathwayStepActivities.activities.length,
    });
    // Filter and sort by date in ascending order (chronological)
    const formActivitiesInCurrentStep = activities.pathwayStepActivities.activities
        .filter((a) => a.object.type === 'FORM' &&
        a.status === 'DONE' &&
        a.date <= currentActivity.date)
        .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
    logDebug(log, 'Selected completed form activities in current step', {
        activityId,
        pathwayId,
        stepId: currentStepId,
        selectedForms: formActivitiesInCurrentStep.map((formActivity) => ({
            formActivityId: formActivity.id,
            formId: formActivity.object.id,
            date: formActivity.date,
        })),
    });
    if ((0, lodash_1.isEmpty)(formActivitiesInCurrentStep))
        return [];
    const getFormDefinitionAndFormResponse = async (formActivity) => {
        var _a, _b;
        const formDefinition = await awellSdk.orchestration.query({
            form: {
                __args: {
                    id: formActivity.object.id,
                },
                form: {
                    __scalar: true,
                    questions: {
                        __scalar: true,
                        options: {
                            __scalar: true,
                        },
                    },
                },
            },
        });
        logDebug(log, 'Fetched form definition', {
            activityId,
            formActivityId: formActivity.id,
            formId: formActivity.object.id,
            questionCount: (_b = (_a = formDefinition.form.form) === null || _a === void 0 ? void 0 : _a.questions.length) !== null && _b !== void 0 ? _b : 0,
        });
        const formResponse = await awellSdk.orchestration.query({
            formResponse: {
                __args: {
                    pathway_id: pathwayId,
                    activity_id: formActivity.id,
                },
                response: {
                    answers: {
                        __scalar: true,
                    },
                },
            },
        });
        logDebug(log, 'Fetched form response', {
            activityId,
            formActivityId: formActivity.id,
            formId: formActivity.object.id,
            answerCount: formResponse.formResponse.response.answers.length,
        });
        return {
            formDefinition: formDefinition.form.form,
            formResponse: formResponse.formResponse.response,
        };
    };
    return await Promise.all(formActivitiesInCurrentStep.map(async (formActivity) => {
        const { formDefinition, formResponse } = await getFormDefinitionAndFormResponse(formActivity);
        return {
            formActivityId: formActivity.id,
            formId: formActivity.object.id,
            formDefinition,
            formResponse,
        };
    }));
};
exports.getAllFormsInCurrentStep = getAllFormsInCurrentStep;
//# sourceMappingURL=getAllFormsInCurrentStep.js.map