"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.listFormAnswers = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const zod_1 = require("zod");
const awell_1 = require("../../../../../src/lib/awell");
const generateFormOutput_1 = require("./lib/generateFormOutput");
exports.listFormAnswers = {
    key: 'listFormAnswers',
    category: extensions_core_1.Category.WORKFLOW,
    title: 'List form answers',
    description: 'List form answers',
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: false,
    supports_automated_retries: true,
    onEvent: async ({ payload, onComplete, onError, helpers }) => {
        const { fields: { scope, formSelection, language, includeDescriptions, includeMissingAnswers, separator, }, } = (0, extensions_core_1.validate)({
            schema: zod_1.z.object({
                fields: config_1.FieldsValidationSchema,
            }),
            payload,
        });
        const awellSdk = await helpers.awellSdk();
        try {
            let forms = [];
            if (scope === 'Step') {
                if (formSelection === 'Latest') {
                    const result = await (0, awell_1.getLatestFormInCurrentStep)({
                        awellSdk,
                        pathwayId: payload.pathway.id,
                        activityId: payload.activity.id,
                    });
                    forms = [
                        {
                            ...result,
                            formName: result.formDefinition.title,
                        },
                    ];
                }
                else {
                    const results = await (0, awell_1.getAllFormsInCurrentStep)({
                        awellSdk,
                        pathwayId: payload.pathway.id,
                        activityId: payload.activity.id,
                    });
                    forms = results.map((result) => ({
                        ...result,
                        formName: result.formDefinition.title,
                    }));
                }
            }
            else {
                // scope === 'Track'
                const allFormsInTrack = await (0, awell_1.getFormsInTrack)({
                    awellSdk,
                    pathwayId: payload.pathway.id,
                    activityId: payload.activity.id,
                });
                if (formSelection === 'Latest') {
                    // Get only the most recent form (last one since they're sorted by date ascending)
                    forms =
                        allFormsInTrack.length > 0
                            ? [allFormsInTrack[allFormsInTrack.length - 1]]
                            : [];
                }
                else {
                    forms = allFormsInTrack;
                }
            }
            if (forms.length === 0) {
                await onComplete({
                    data_points: {
                        output: '(No form response)',
                        numberOfFormsCaptured: '0',
                    },
                    events: [
                        (0, awell_1.addActivityEventLog)({
                            message: `No (completed) form action found in the current ${scope.toLowerCase()}`,
                        }),
                    ],
                });
                return;
            }
            const allOmittedFormAnswers = [];
            const formOutputs = [];
            const useFormHeaders = formSelection === 'All';
            for (const form of forms) {
                const { result: formOutput, omittedFormAnswers } = (0, generateFormOutput_1.generateFormOutput)({
                    awellSdk,
                    formDefinition: form.formDefinition,
                    formResponse: form.formResponse,
                    language,
                    includeDescriptions,
                    includeMissingAnswers,
                    separator,
                });
                const outputWithHeader = useFormHeaders
                    ? `=== ${form.formName} ===\n\n${formOutput}`
                    : formOutput;
                formOutputs.push(outputWithHeader);
                allOmittedFormAnswers.push(...omittedFormAnswers);
            }
            const output = formOutputs.join('\n\n');
            await onComplete({
                data_points: {
                    output,
                    numberOfFormsCaptured: String(forms.length),
                },
                events: [
                    (0, awell_1.addActivityEventLog)({
                        message: allOmittedFormAnswers.length > 0
                            ? `Not included in the output:\n ${allOmittedFormAnswers.map((answer) => `${answer.questionKey}: ${answer.reason}`).join('\n')}`
                            : 'All form answers were included in the output',
                    }),
                ],
            });
        }
        catch (error) {
            if (error instanceof Error &&
                error.message === 'No (completed) form action found in the current step') {
                await onComplete({
                    data_points: {
                        output: '(No form response)',
                        numberOfFormsCaptured: '0',
                    },
                    events: [
                        (0, awell_1.addActivityEventLog)({
                            message: error.message,
                        }),
                    ],
                });
            }
            else {
                await onError({
                    events: [
                        (0, awell_1.addActivityEventLog)({
                            message: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`,
                        }),
                    ],
                });
            }
        }
    },
};
//# sourceMappingURL=listFormAnswers.js.map