import * as i0 from '@angular/core';
import { inject, Injectable } from '@angular/core';
import { AXPWorkflowManager } from '@acorex/platform/workflow';
import { AXToastService } from '@acorex/components/toast';
import { Router } from '@angular/router';
import { AXPSessionService } from '@acorex/platform/auth';

//#endregion
/**
 * Execute Workflow Command
 *
 * Starts and manages workflow execution from entity list.
 * Handles the complete workflow lifecycle including frontend/backend activities.
 */
class ExecuteWorkflowCommand {
    constructor() {
        //#region ----   Services   ----
        this.workflowManager = inject(AXPWorkflowManager);
        this.toastService = inject(AXToastService);
    }
    //#endregion
    //#region ----   Command Implementation   ----
    async execute(xx) {
        try {
            // Extract input from command context (entity actions pass options via __context__.options)
            const input = (xx?.__context__?.options || xx);
            console.log(`[WorkflowManagement] 🚀 ExecuteWorkflowCommand: Starting workflow '${input.workflowId}'`, {
                workflowId: input.workflowId,
                input: input.input,
                context: xx?.__context__,
            });
            // Start workflow execution
            // This uses the workflow engine which now queries definitions by name field
            const result = await this.workflowManager.start(input.workflowId, input.input || {});
            console.log(`[WorkflowManagement] 📊 Workflow start result:`, {
                success: result.success,
                instanceId: result.instanceId,
                error: result.error,
                stateStatus: result.state?.status,
                stateActivityOutputs: result.state?.activityOutputs,
            });
            if (!result.success) {
                console.error(`[WorkflowManagement] ❌ Failed to start workflow '${input.workflowId}':`, result.error);
                this.toastService.show({
                    color: 'danger',
                    title: 'Workflow Execution Failed',
                    content: result.error || 'Unknown error',
                    closeButton: true,
                    timeOut: 5000,
                });
                return {
                    success: false,
                    message: {
                        text: result.error || 'Unknown error'
                    },
                    data: {
                        instanceId: result.instanceId || '',
                        output: null,
                    }
                };
            }
            console.log(`[WorkflowManagement] ✅ Workflow '${input.workflowId}' started successfully. Instance ID: ${result.instanceId}`);
            // Handle workflow execution loop
            // let currentResult = result;
            // let taskCount = 0;
            // while (currentResult.nextTask) {
            //   taskCount++;
            //   const task = currentResult.nextTask;
            //   console.log(`[ExecuteWorkflowCommand] 🔄 Task ${taskCount}: Executing frontend task: ${task.activityType}`, task);
            //   // Execute frontend task
            //   console.log(`[ExecuteWorkflowCommand] ⚙️ Calling workflowManager.execute...`);
            //   const executionResult = await this.workflowManager.execute(task);
            //   console.log(`[ExecuteWorkflowCommand] ✅ Task executed:`, {
            //     output: executionResult.output,
            //     outcome: executionResult.outcome,
            //   });
            //   const { output, outcome } = executionResult;
            //   // Complete task and get next
            //   currentResult = await this.workflowManager.complete(
            //     currentResult.instanceId!,
            //     task,
            //     outcome,
            //     output
            //   );
            //   if (!currentResult.success) {
            //     this.toastService.show({
            //       color: 'danger',
            //       title: 'Workflow Execution Failed',
            //       content: currentResult.error || 'Unknown error',
            //       closeButton: true,
            //       timeOut: 5000,
            //     });
            //     return {
            //       success: false,
            //       message: {
            //         text: currentResult.error || 'Unknown error'
            //       },
            //       data: {
            //         instanceId: currentResult.instanceId || '',
            //         output: null,
            //       }
            //     };
            //   }
            // }
            // Workflow completed successfully
            // console.log(`[ExecuteWorkflowCommand] Workflow completed:`, currentResult.state?.output);
            return {
                success: true,
                //   data: {
                //     instanceId: currentResult.instanceId!,
                //     output: currentResult.state?.output,
                //   }
            };
        }
        catch (error) {
            console.error(`[ExecuteWorkflowCommand] Error:`, error);
            this.toastService.show({
                color: 'danger',
                title: 'Workflow Execution Error',
                content: error.message || 'Unknown error',
                closeButton: true,
                timeOut: 5000,
            });
            return {
                success: false,
                message: {
                    text: error.message || 'Unknown error'
                },
                data: {
                    instanceId: '',
                    output: null,
                }
            };
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: ExecuteWorkflowCommand, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: ExecuteWorkflowCommand }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: ExecuteWorkflowCommand, decorators: [{
            type: Injectable
        }] });

//#endregion
/**
 * Edit In Studio Command
 *
 * Navigates to workflow studio with the specified workflow definition.
 */
class EditInStudioCommand {
    constructor() {
        //#region ----   Services & Dependencies   ----
        this.router = inject(Router);
        this.sessionService = inject(AXPSessionService);
    }
    //#endregion
    //#region ----   Command Implementation   ----
    async execute(input) {
        try {
            const appName = this.sessionService.application?.name;
            if (!appName) {
                return {
                    success: false,
                    message: {
                        text: 'Application name not found',
                    },
                    data: {
                        navigated: false,
                    },
                };
            }
            const studioPath = `${appName}/workflow-management/studio`;
            await this.router.navigate([studioPath], {
                queryParams: {
                    workflow: input.workflowName,
                },
            });
            return {
                success: true,
                data: {
                    navigated: true,
                },
            };
        }
        catch (error) {
            return {
                success: false,
                message: {
                    text: error.message || 'Failed to navigate to workflow studio',
                },
                data: {
                    navigated: false,
                },
            };
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: EditInStudioCommand, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: EditInStudioCommand }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: EditInStudioCommand, decorators: [{
            type: Injectable
        }] });

export { EditInStudioCommand, ExecuteWorkflowCommand };
//# sourceMappingURL=acorex-modules-workflow-management-index-BYSJb8d8.mjs.map
