import { Request, Response } from 'express';
import { WorkflowTask } from '../src/pages/WorkflowOrchestrator/data';

// 模拟内存数据库
let workflowData: WorkflowTask[] = [
    {
        id: 'wf-001',
        name: '自动化 UI 部署任务',
        status: 'executing',
        progress: 30,
        currentStepId: 'step-2',
        createTime: '2024-03-20 10:00:00',
        steps: [
            { id: 'step-1', agentName: 'Planning Agent', status: 'success', startTime: '10:00', logs: '已完成架构设计与需求拆解。' },
            { id: 'step-2', agentName: 'Frontend Agent', status: 'executing', startTime: '10:05', logs: '正在编写 ProTable 组件代码，应用 Design Tokens...' },
            { id: 'step-3', agentName: 'QA Agent', status: 'thinking', startTime: '10:10', logs: '待执行回归测试。' },
        ],
    },
    {
        id: 'wf-002',
        name: '后端 API 重构',
        status: 'success',
        progress: 100,
        currentStepId: 'step-2',
        createTime: '2024-03-20 09:30:00',
        steps: [
            { id: 'step-1', agentName: 'Architect', status: 'success', startTime: '09:30', logs: 'API 路径规范化已通过。' },
            { id: 'step-2', agentName: 'Backend Dev', status: 'success', startTime: '09:45', logs: '完成 Swagger 契约自动生成。' },
        ],
    },
    {
        id: 'wf-003',
        name: '性能压力测试',
        status: 'failed',
        progress: 65,
        currentStepId: 'step-2',
        createTime: '2024-03-20 11:00:00',
        steps: [
            { id: 'step-1', agentName: 'DevOps Agent', status: 'success', startTime: '11:00', logs: '环境已就绪。' },
            { id: 'step-2', agentName: 'QA Agent', status: 'failed', startTime: '11:15', logs: '内存溢出错误：JVM heap size exceeded.' },
        ],
    },
];

export default {
    'GET /api/workflow/list': (req: Request, res: Response) => {
        // 动态更新逻辑：每次列表请求都模拟进度步进
        workflowData = workflowData.map((task) => {
            if (task.status === 'executing' && task.progress < 100) {
                const nextProgress = Math.min(task.progress + 5, 100);
                return {
                    ...task,
                    progress: nextProgress,
                    status: nextProgress === 100 ? 'success' : 'executing',
                };
            }
            return task;
        });
        res.send({ data: workflowData, total: workflowData.length });
    },

    'POST /api/workflow/:id/control': (req: Request, res: Response) => {
        const { id } = req.params;
        const { action } = req.body;
        workflowData = workflowData.map((task) => {
            if (task.id === id) {
                if (action === 'retry') return { ...task, status: 'executing', progress: 0 };
                if (action === 'stop') return { ...task, status: 'failed' };
            }
            return task;
        });
        res.send({ success: true });
    },
};
