// mock-tasks.ts
import { FlowTask } from '../../lib/flow.task';

export class MockSuccessTask extends FlowTask {
  constructor() {
    super({
      title: '初始化系统',
      input: [
        { name: 'config', type: 'object', required: true, description: '系统配置对象' }
      ],
      output: [
        { name: 'result', type: 'string', description: '初始化结果' },
        { name: 'timestamp', type: 'number', description: '完成时间戳' }
      ],
      initialData: {
        description: '系统初始化配置',
        config: { env: 'production' } // 提供默认配置
      }
    });
  }

  override async handle() {
    // 模拟初始化过程
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 验证输入
    if (!this.getData('config')) {
      throw new Error('缺少必要配置');
    }

    // 设置输出
    this.updateData('result', '初始化成功')
       .updateData('timestamp', Date.now());
    this.setProgress(1);
  }
}

export class MockRetryTask extends FlowTask {
  private static readonly MAX_ATTEMPTS = 3;

  constructor() {
    super({
      title: '数据同步',
      output: [
        { name: 'syncResult', type: 'object', description: '同步结果数据' }
      ],
      initialData: {
        description: '尝试连接远程服务器',
        serverUrl: 'https://api.example.com'
      }
    });
  }

  override async handle() {
    // 模拟连接尝试
    await new Promise(resolve => setTimeout(resolve, 300));

    // 模拟75%成功率
    const shouldFail = Math.random() < 0.75;
    if (shouldFail && this.attempts < MockRetryTask.MAX_ATTEMPTS - 1) {
      this.attempts++;
      throw new Error(`第 ${this.attempts} 次连接失败`);
    }

    // 成功情况
    this.updateData('syncResult', {
      connected: true,
      server: this.getData('serverUrl'),
      dataReceived: Array(5).fill(0).map((_,i) => `item_${i+1}`)
    });
    this.setProgress(1);
  }

  private get attempts(): number {
    return this.getData('_attempts') || 0;
  }

  private set attempts(value: number) {
    this.updateData('_attempts', value);
  }
}

export class MockProgressTask extends FlowTask {
  constructor() {
    super({
      title: '数据处理',
      output: [
        { name: 'processedItems', type: 'array' },
        { name: 'stats', type: 'object' }
      ],
      initialData: {
        description: '批量处理数据记录',
        batchSize: 100
      }
    });
  }

  override async handle() {
    const batchSize = this.getData('batchSize') || 100;
    const results = [];

    for (let i = 1; i <= batchSize; i++) {
      await new Promise(resolve => setTimeout(resolve, 20));

      // 模拟数据处理
      results.push({
        id: i,
        processedAt: Date.now(),
        value: Math.random().toString(36).substring(7)
      });

      // 每10%更新一次进度
      if (i % (batchSize/10) === 0) {
        this.setProgress(i / batchSize);
      }
    }

    // 最终输出
    this.updateData('processedItems', results)
       .updateData('stats', {
         total: results.length,
         avgTime: 20,
         firstId: results[0]?.id,
         lastId: results[results.length-1]?.id
       });
  }
}
