import { AXTranslationService } from '@acorex/core/translation';
import { AXPSessionService } from '@acorex/platform/auth';
import * as i0 from '@angular/core';
import { inject, Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { get } from 'lodash-es';
import { A as AXMQuestionnaireViewerService } from './acorex-modules-assessment-management-questionnaire-viewer.service-BwxkdgXr.mjs';
import { b as AXMAssessmentCaseService, A as AXMQuestionnaireService, a as AXMAssessmentSessionService, R as RootConfig, t as toPrePostConfig } from './acorex-modules-assessment-management-acorex-modules-assessment-management-W8hHssaa.mjs';

//#endregion
//#region ----   Fill Assessment Session Command   ----
/**
 * Command that opens questionnaire viewer for filling/editing assessment session.
 */
class FillAssessmentSessionCommand {
    constructor() {
        //#region ----   Services & Dependencies   ----
        this.sessionService = inject(AXPSessionService);
        this.router = inject(Router);
        this.caseService = inject(AXMAssessmentCaseService);
        this.questionnaireService = inject(AXMQuestionnaireService);
        this.assessmentSessionService = inject(AXMAssessmentSessionService);
        this.questionnaireViewerService = inject(AXMQuestionnaireViewerService);
        this.translationService = inject(AXTranslationService);
    }
    //#endregion
    //#region ----   Utility Methods   ----
    /**
     * Calculate answered questions count and progress percentage from questionnaire structure and answers
     */
    calculateProgress(structure, answers) {
        if (!structure?.sections || structure.sections.length === 0) {
            return { answeredQuestionsCount: 0, progressPercentage: 0 };
        }
        let totalQuestions = 0;
        let answeredCount = 0;
        for (const section of structure.sections) {
            if (!section.items || section.items.length === 0)
                continue;
            for (const item of section.items) {
                totalQuestions++;
                // Get the answer path - use item.id if available, otherwise use index-based path
                const answerPath = item.id ? `answers.${item.id}` : null;
                // Try to get answer value
                let answerValue = null;
                if (answerPath) {
                    answerValue = get(answers, answerPath);
                }
                else {
                    // Fallback: try to find answer by checking all answer keys
                    // This is less precise but handles cases where path might not match exactly
                    const sectionIndex = structure.sections.indexOf(section);
                    const itemIndex = section.items.indexOf(item);
                    const fallbackPath = `answers.${sectionIndex}-${itemIndex}`;
                    answerValue = get(answers, fallbackPath);
                }
                // Check if answer is not empty
                const isEmpty = answerValue === null ||
                    answerValue === undefined ||
                    answerValue === '' ||
                    (Array.isArray(answerValue) && answerValue.length === 0) ||
                    (typeof answerValue === 'object' && Object.keys(answerValue).length === 0);
                if (!isEmpty) {
                    answeredCount++;
                }
            }
        }
        const progressPercentage = totalQuestions > 0 ? Math.round((answeredCount / totalQuestions) * 100) : 0;
        return { answeredQuestionsCount: answeredCount, progressPercentage };
    }
    //#endregion
    //#region ----   Command Implementation   ----
    async execute(input) {
        try {
            // Get assessment case
            const assessmentCase = await this.caseService.getOne(input.caseId);
            if (!assessmentCase) {
                return {
                    success: false,
                    message: {
                        text: `Assessment case with ID ${input.caseId} not found`,
                    },
                };
            }
            // Get questionnaire
            const questionnaire = await this.questionnaireService.getOne(assessmentCase.questionnaireId);
            if (!questionnaire) {
                return {
                    success: false,
                    message: {
                        text: `Questionnaire with ID ${assessmentCase.questionnaireId} not found`,
                    },
                };
            }
            // Check if questionnaire has structure
            const structure = questionnaire.structure;
            if (!structure || !structure.sections || structure.sections.length === 0) {
                return {
                    success: false,
                    message: {
                        text: 'Questionnaire has no structure to display',
                    },
                };
            }
            // Get current user if responderId not provided
            const currentUser = this.sessionService.user;
            const responderId = input.responderId || currentUser?.id;
            if (!responderId) {
                return {
                    success: false,
                    message: {
                        text: 'No responder ID provided and no current user found',
                    },
                };
            }
            // Default role to 'responder' if not provided
            const role = input.role || 'responder';
            // Load existing session if sessionId is provided
            let existingSession = null;
            let initialAnswers = {};
            if (input.sessionId) {
                existingSession = await this.assessmentSessionService.getOne(input.sessionId);
                if (existingSession) {
                    initialAnswers = existingSession.answers || {};
                }
            }
            const showAs = input.showAs ?? 'popup';
            const appName = this.sessionService.application?.name ?? 'demo';
            const moduleRoute = RootConfig.module.route ?? 'assessment-management';
            // Navigate to in-app page (inside root layout)
            if (showAs === 'page') {
                const path = `/${appName}/${moduleRoute}/questionnaire/fill/${input.caseId}`;
                const url = input.sessionId ? `${path}?sessionId=${encodeURIComponent(input.sessionId)}` : path;
                this.router.navigateByUrl(url);
                return { success: true };
            }
            // Navigate to standalone page (external, no app shell)
            if (showAs === 'standalone') {
                let sessionIdToOpen = input.sessionId;
                if (!sessionIdToOpen) {
                    const now = new Date();
                    const newSession = await this.assessmentSessionService.insertOne({
                        caseId: input.caseId,
                        responderId: responderId,
                        role: role,
                        answers: {},
                        progressPercentage: 0,
                        answeredQuestionsCount: 0,
                        lastSavedAt: now,
                        startedAt: now,
                    });
                    sessionIdToOpen = newSession?.id ?? newSession;
                }
                if (sessionIdToOpen) {
                    this.router.navigateByUrl(`/assessment/fill/${sessionIdToOpen}`);
                }
                return { success: true };
            }
            // Get fill title (popup mode)
            const fillTitleKey = '@assessment-management:cases.actions.fill-assessment.title';
            const fillTitleBase = await this.translationService.translateAsync(fillTitleKey);
            const fillTitle = fillTitleBase || 'Fill Assessment';
            // Submit handler for popup - saves session and returns result for summary
            const submitHandler = async (answers) => {
                const { answeredQuestionsCount, progressPercentage } = this.calculateProgress(structure, answers);
                const now = new Date();
                const sessionData = {
                    caseId: input.caseId,
                    responderId: responderId,
                    role: role,
                    answers,
                    progressPercentage,
                    answeredQuestionsCount,
                    lastSavedAt: now,
                };
                if (!existingSession) {
                    sessionData.startedAt = now;
                }
                if (!existingSession) {
                    sessionData.statusId = 'not-started';
                }
                else {
                    const currentStatusId = existingSession.statusId;
                    sessionData.statusId = currentStatusId === 'not-started' ? 'in-progress' : currentStatusId;
                }
                if (existingSession) {
                    await this.assessmentSessionService.updateOne(existingSession.id, sessionData);
                }
                else {
                    await this.assessmentSessionService.insertOne(sessionData);
                }
                const totalQuestions = structure.sections?.reduce((s, sec) => s + (sec.items?.length ?? 0), 0) ?? 0;
                return {
                    score: progressPercentage,
                    totalQuestions,
                    answeredCount: answeredQuestionsCount,
                };
            };
            // Open questionnaire viewer in edit mode (popup)
            const result = await this.questionnaireViewerService.open({
                title: fillTitle,
                structure,
                prePostConfig: toPrePostConfig(questionnaire),
                size: 'lg',
                config: {
                    readonly: false, // Edit mode - answers can be edited
                },
                initialAnswers: initialAnswers,
                submitHandler,
            });
            // If user submitted (not just closed) - session was already saved by submitHandler in popup flow
            if (result && result.submitted && result.answers) {
                return {
                    success: true,
                };
            }
            // User closed without submitting
            return {
                success: true,
            };
        }
        catch (error) {
            console.error('Error filling assessment session:', error);
            return {
                success: false,
                message: {
                    text: `Error filling assessment session: ${error.message || 'Unknown error'}`,
                },
            };
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: FillAssessmentSessionCommand, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: FillAssessmentSessionCommand }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: FillAssessmentSessionCommand, decorators: [{
            type: Injectable
        }] });

export { FillAssessmentSessionCommand };
//# sourceMappingURL=acorex-modules-assessment-management-fill-assessment-session.command-CaDLclxt.mjs.map
