/**
 * [MOCK-AI-TASK] AI Action Task Manager DataSource
 * AI注意: 这是Mock实现，不是真实业务逻辑
 * 仅在USE_MOCK=true时启用
 */

export interface AITask {
  id: string;
  taskId: string;
  name: string;
  actionType: string;
  status: 'PENDING' | 'AI_ANALYZING' | 'PENDING_REVIEW' | 'APPROVED' | 'REJECTED' | 'AI_EXECUTING' | 'COMPLETED' | 'FAILED';
  priority: 'LOW' | 'MEDIUM' | 'HIGH' | 'URGENT';
  progress: number;
  createdAt: string;
  startedAt?: string;
  completedAt?: string;
  estimatedDuration: number;
  actualDuration?: number;
  retryCount: number;
  maxRetries: number;
  shopId: string;
  shopName: string;
  createdBy: string;
  aiSuggestion?: any;
  humanDecision?: 'APPROVED' | 'REJECTED' | 'PENDING';
  executionResult?: any;
  errorMessage?: string;
}

export interface AIActionTaskDataSource {
  fetchTasks(params?: {
    status?: string;
    actionType?: string;
    priority?: string;
    search?: string;
  }): Promise<AITask[]>;
  
  getTask(id: string): Promise<AITask | null>;
  
  createTask(task: Omit<AITask, 'id' | 'taskId' | 'status' | 'progress' | 'createdAt' | 'retryCount'>): Promise<AITask>;
  
  updateTask(id: string, task: Partial<AITask>): Promise<AITask | null>;
  
  startTask(taskId: string): Promise<AITask | null>;
  
  pauseTask(taskId: string): Promise<AITask | null>;
  
  stopTask(taskId: string): Promise<AITask | null>;
  
  retryTask(taskId: string): Promise<AITask | null>;
  
  deleteTask(taskId: string): Promise<boolean>;
  
  approveTask(taskId: string): Promise<AITask | null>;
  
  rejectTask(taskId: string): Promise<AITask | null>;
  
  getTaskStats(): Promise<{
    total: number;
    pending: number;
    analyzing: number;
    pendingReview: number;
    approved: number;
    rejected: number;
    executing: number;
    completed: number;
    failed: number;
  }>;
}

export class AIActionTaskDataSourceImpl implements AIActionTaskDataSource {
  private mockTasks: AITask[] = [
    {
      id: '1',
      taskId: 'AIA-2026-001',
      name: 'Pricing Optimization - Electronics',
      actionType: 'PRICING_OPTIMIZATION',
      status: 'PENDING_REVIEW',
      priority: 'HIGH',
      progress: 33,
      createdAt: '2026-03-18 10:00:00',
      startedAt: '2026-03-18 10:05:00',
      estimatedDuration: 30,
      retryCount: 0,
      maxRetries: 3,
      shopId: 'SHOP_001',
      shopName: 'Amazon US Store',
      createdBy: 'admin',
      aiSuggestion: {
        suggestedPrice: 89.99,
        currentPrice: 79.99,
        reason: 'Based on competitor analysis and sales trends',
        expectedImpact: '15% increase in sales volume',
      },
      humanDecision: 'PENDING',
    },
    {
      id: '2',
      taskId: 'AIA-2026-002',
      name: 'Order Processing - Batch 001',
      actionType: 'ORDER_PROCESSING',
      status: 'COMPLETED',
      priority: 'URGENT',
      progress: 100,
      createdAt: '2026-03-18 09:00:00',
      startedAt: '2026-03-18 09:01:00',
      completedAt: '2026-03-18 09:15:00',
      estimatedDuration: 15,
      actualDuration: 14,
      retryCount: 0,
      maxRetries: 3,
      shopId: 'SHOP_002',
      shopName: 'eBay Outlet',
      createdBy: 'admin',
      aiSuggestion: {
        batchSize: 150,
        processingMethod: 'automated',
        estimatedTime: '15 minutes',
      },
      humanDecision: 'APPROVED',
      executionResult: { processedOrders: 150, successCount: 148, failedCount: 2 },
    },
    {
      id: '3',
      taskId: 'AIA-2026-003',
      name: 'Inventory Management - Seasonal',
      actionType: 'INVENTORY_MANAGEMENT',
      status: 'AI_ANALYZING',
      priority: 'MEDIUM',
      progress: 65,
      createdAt: '2026-03-18 08:00:00',
      startedAt: '2026-03-18 08:05:00',
      estimatedDuration: 60,
      retryCount: 0,
      maxRetries: 3,
      shopId: 'SHOP_003',
      shopName: 'Shopify Brand Store',
      createdBy: 'admin',
    },
    {
      id: '4',
      taskId: 'AIA-2026-004',
      name: 'Marketing Campaign - Summer Sale',
      actionType: 'MARKETING_CAMPAIGN',
      status: 'AI_EXECUTING',
      priority: 'HIGH',
      progress: 75,
      createdAt: '2026-03-18 07:30:00',
      startedAt: '2026-03-18 07:31:00',
      estimatedDuration: 45,
      retryCount: 0,
      maxRetries: 3,
      shopId: 'SHOP_001',
      shopName: 'Amazon US Store',
      createdBy: 'admin',
      aiSuggestion: {
        campaignBudget: 1000,
        targetAudience: '25-34 year olds',
        channels: ['Facebook', 'Instagram', 'Google Ads'],
        expectedROI: '3:1',
      },
      humanDecision: 'APPROVED',
    },
    {
      id: '5',
      taskId: 'AIA-2026-005',
      name: 'Product Optimization - Electronics',
      actionType: 'PRODUCT_OPTIMIZATION',
      status: 'FAILED',
      priority: 'MEDIUM',
      progress: 45,
      createdAt: '2026-03-18 06:00:00',
      startedAt: '2026-03-18 06:01:00',
      estimatedDuration: 45,
      actualDuration: 30,
      retryCount: 2,
      maxRetries: 3,
      shopId: 'SHOP_004',
      shopName: 'Shopee Mall',
      createdBy: 'admin',
      errorMessage: 'API rate limit exceeded. Please retry later.',
    },
    {
      id: '6',
      taskId: 'AIA-2026-006',
      name: 'Custom Action - Data Export',
      actionType: 'CUSTOM',
      status: 'PENDING',
      priority: 'LOW',
      progress: 0,
      createdAt: '2026-03-17 18:00:00',
      estimatedDuration: 30,
      retryCount: 0,
      maxRetries: 3,
      shopId: 'SHOP_005',
      shopName: 'Lazada Store',
      createdBy: 'user1',
    },
  ];

  async fetchTasks(params?: {
    status?: string;
    actionType?: string;
    priority?: string;
    search?: string;
  }): Promise<AITask[]> {
    let filtered = [...this.mockTasks];

    if (params?.status) {
      filtered = filtered.filter(task => task.status === params.status);
    }

    if (params?.actionType) {
      filtered = filtered.filter(task => task.actionType === params.actionType);
    }

    if (params?.priority) {
      filtered = filtered.filter(task => task.priority === params.priority);
    }

    if (params?.search) {
      const searchLower = params.search.toLowerCase();
      filtered = filtered.filter(
        task =>
          (task.taskId || '').toLowerCase().includes(searchLower) ||
          task.name.toLowerCase().includes(searchLower)
      );
    }

    return filtered;
  }

  async getTask(id: string): Promise<AITask | null> {
    const task = this.mockTasks.find(t => t.id === id || t.taskId === id);
    return task || null;
  }

  async createTask(task: Omit<AITask, 'id' | 'taskId' | 'status' | 'progress' | 'createdAt' | 'retryCount'>): Promise<AITask> {
    const newTask: AITask = {
      ...task,
      id: `${this.mockTasks.length + 1}`,
      taskId: `AIA-2026-${String(this.mockTasks.length + 1).padStart(3, '0')}`,
      status: 'PENDING',
      progress: 0,
      createdAt: new Date().toISOString(),
      retryCount: 0,
    };
    this.mockTasks.push(newTask);
    return newTask;
  }

  async updateTask(id: string, task: Partial<AITask>): Promise<AITask | null> {
    const index = this.mockTasks.findIndex(t => t.id === id || t.taskId === id);
    if (index === -1) {
      return null;
    }
    this.mockTasks[index] = { ...this.mockTasks[index], ...task };
    return this.mockTasks[index];
  }

  async startTask(taskId: string): Promise<AITask | null> {
    const task = await this.getTask(taskId);
    if (!task) return null;
    
    task.status = 'AI_ANALYZING';
    task.startedAt = new Date().toISOString();
    task.progress = 10;
    
    return task;
  }

  async pauseTask(taskId: string): Promise<AITask | null> {
    const task = await this.getTask(taskId);
    if (!task) return null;
    
    task.status = 'PENDING';
    
    return task;
  }

  async stopTask(taskId: string): Promise<AITask | null> {
    const task = await this.getTask(taskId);
    if (!task) return null;
    
    task.status = 'FAILED';
    task.errorMessage = 'Task stopped by user';
    task.completedAt = new Date().toISOString();
    
    return task;
  }

  async retryTask(taskId: string): Promise<AITask | null> {
    const task = await this.getTask(taskId);
    if (!task) return null;
    
    task.status = 'PENDING';
    task.retryCount += 1;
    task.progress = 0;
    
    return task;
  }

  async deleteTask(taskId: string): Promise<boolean> {
    const index = this.mockTasks.findIndex(t => t.id === taskId || t.taskId === taskId);
    if (index === -1) {
      return false;
    }
    this.mockTasks.splice(index, 1);
    return true;
  }

  async approveTask(taskId: string): Promise<AITask | null> {
    const task = await this.getTask(taskId);
    if (!task) return null;
    
    task.status = 'APPROVED';
    task.humanDecision = 'APPROVED';
    
    return task;
  }

  async rejectTask(taskId: string): Promise<AITask | null> {
    const task = await this.getTask(taskId);
    if (!task) return null;
    
    task.status = 'REJECTED';
    task.humanDecision = 'REJECTED';
    
    return task;
  }

  async getTaskStats(): Promise<{
    total: number;
    pending: number;
    analyzing: number;
    pendingReview: number;
    approved: number;
    rejected: number;
    executing: number;
    completed: number;
    failed: number;
  }> {
    const total = this.mockTasks.length;
    const pending = this.mockTasks.filter(t => t.status === 'PENDING').length;
    const analyzing = this.mockTasks.filter(t => t.status === 'AI_ANALYZING').length;
    const pendingReview = this.mockTasks.filter(t => t.status === 'PENDING_REVIEW').length;
    const approved = this.mockTasks.filter(t => t.status === 'APPROVED').length;
    const rejected = this.mockTasks.filter(t => t.status === 'REJECTED').length;
    const executing = this.mockTasks.filter(t => t.status === 'AI_EXECUTING').length;
    const completed = this.mockTasks.filter(t => t.status === 'COMPLETED').length;
    const failed = this.mockTasks.filter(t => t.status === 'FAILED').length;

    return {
      total,
      pending,
      analyzing,
      pendingReview,
      approved,
      rejected,
      executing,
      completed,
      failed,
    };
  }
}

export const aiActionTaskDataSource = new AIActionTaskDataSourceImpl();