/**
 * [MOCK-014] 人工审批模块DataSource
 * AI注意: 这是Mock实现，不是真实业务逻辑
 * 仅在USE_MOCK=true时启用 */

export interface Task {
  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 HumanApprovalDataSource {
  fetchTasks(params?: {
    status?: string;
    actionType?: string;
    priority?: string;
    search?: string;
  }): Promise<Task[]>;
  getTask(id: string): Promise<Task | null>;
  approveTask(id: string, formData: any): Promise<Task | null>;
  rejectTask(id: string, reason: string): Promise<Task | null>;
  modifyTask(id: string, modifiedData: any): Promise<Task | null>;
  getTaskStats(): Promise<{
    total: number;
    pending: number;
    approved: number;
    rejected: number;
  }>;
}

export class HumanApprovalDataSourceImpl implements HumanApprovalDataSource {
  private tasks: Task[] = [
    {
      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: {
        title: 'Adjust price for iPhone 14 Pro Max',
        description: 'Based on competitor analysis and sales trends, we recommend adjusting the price of iPhone 14 Pro Max from $999 to $949 to increase sales volume by 15%.',
        suggestedPrice: 949,
        currentPrice: 799,
        reason: 'Based on competitor analysis and sales trends',
        expectedImpact: '15% increase in sales volume',
        confidence: 'high',
        priority: 'high',
      },
      humanDecision: 'PENDING',
    },
    {
      id: '2',
      taskId: 'AIA-2026-002',
      name: 'Order Processing - Batch 001',
      actionType: 'ORDER_PROCESSING',
      status: 'PENDING_REVIEW',
      priority: 'URGENT',
      progress: 33,
      createdAt: '2026-03-18 09:00:00',
      startedAt: '2026-03-18 09:01:00',
      estimatedDuration: 15,
      retryCount: 0,
      maxRetries: 3,
      shopId: 'SHOP_002',
      shopName: 'eBay Outlet',
      createdBy: 'admin',
      aiSuggestion: {
        title: 'Process batch order 001',
        description: 'Process 150 orders in batch 001 with automated processing method.',
        batchSize: 150,
        processingMethod: 'automated',
        estimatedTime: '15 minutes',
        confidence: 'high',
        priority: 'urgent',
      },
      humanDecision: 'PENDING',
    },
    {
      id: '3',
      taskId: 'AIA-2026-003',
      name: 'Marketing Campaign - Summer Sale',
      actionType: 'MARKETING_CAMPAIGN',
      status: 'PENDING_REVIEW',
      priority: 'MEDIUM',
      progress: 33,
      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',
      aiSuggestion: {
        title: 'Launch summer sale campaign',
        description: 'Launch a summer sale campaign with 15% discount on selected items.',
        campaignBudget: 1000,
        targetAudience: '25-34 year olds',
        channels: ['Facebook', 'Instagram', 'Google Ads'],
        expectedROI: '3:1',
        confidence: 'medium',
        priority: 'medium',
      },
      humanDecision: 'PENDING',
    },
    {
      id: '4',
      taskId: 'AIA-2026-004',
      name: 'Inventory Management - Seasonal',
      actionType: 'INVENTORY_MANAGEMENT',
      status: 'APPROVED',
      priority: 'HIGH',
      progress: 66,
      createdAt: '2026-03-17 18:00:00',
      startedAt: '2026-03-17 18:05:00',
      estimatedDuration: 45,
      retryCount: 0,
      maxRetries: 3,
      shopId: 'SHOP_004',
      shopName: 'Shopee Mall',
      createdBy: 'admin',
      aiSuggestion: {
        title: 'Restock seasonal inventory',
        description: 'Restock 500 units of seasonal inventory to prepare for upcoming demand.',
        confidence: 'high',
        priority: 'high',
      },
      humanDecision: 'APPROVED',
    },
    {
      id: '5',
      taskId: 'AIA-2026-005',
      name: 'Product Optimization - Electronics',
      actionType: 'PRODUCT_OPTIMIZATION',
      status: 'REJECTED',
      priority: 'MEDIUM',
      progress: 33,
      createdAt: '2026-03-17 16:00:00',
      startedAt: '2026-03-17 16:05:00',
      estimatedDuration: 30,
      retryCount: 0,
      maxRetries: 3,
      shopId: 'SHOP_001',
      shopName: 'Amazon US Store',
      createdBy: 'admin',
      aiSuggestion: {
        title: 'Optimize product listings',
        description: 'Optimize product listings for better search visibility.',
        confidence: 'medium',
        priority: 'medium',
      },
      humanDecision: 'REJECTED',
    },
  ];

  async fetchTasks(params?: {
    status?: string;
    actionType?: string;
    priority?: string;
    search?: string;
  }): Promise<Task[]> {
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 500));

    let filteredTasks = [...this.tasks];

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

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

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

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

    return filteredTasks;
  }

  async getTask(id: string): Promise<Task | null> {
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 300));

    const task = this.tasks.find(task => task.id === id);
    return task || null;
  }

  async approveTask(id: string, formData: any): Promise<Task | null> {
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 1000));

    const taskIndex = this.tasks.findIndex(task => task.id === id);
    if (taskIndex === -1) {
      return null;
    }

    this.tasks[taskIndex] = {
      ...this.tasks[taskIndex],
      status: 'APPROVED',
      humanDecision: 'APPROVED',
      progress: 66,
    };

    return this.tasks[taskIndex];
  }

  async rejectTask(id: string, reason: string): Promise<Task | null> {
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 1000));

    const taskIndex = this.tasks.findIndex(task => task.id === id);
    if (taskIndex === -1) {
      return null;
    }

    this.tasks[taskIndex] = {
      ...this.tasks[taskIndex],
      status: 'REJECTED',
      humanDecision: 'REJECTED',
      errorMessage: reason,
    };

    return this.tasks[taskIndex];
  }

  async modifyTask(id: string, modifiedData: any): Promise<Task | null> {
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 1000));

    const taskIndex = this.tasks.findIndex(task => task.id === id);
    if (taskIndex === -1) {
      return null;
    }

    this.tasks[taskIndex] = {
      ...this.tasks[taskIndex],
      status: 'APPROVED',
      humanDecision: 'APPROVED',
      progress: 66,
      aiSuggestion: {
        ...this.tasks[taskIndex].aiSuggestion,
        ...modifiedData,
      },
    };

    return this.tasks[taskIndex];
  }

  async getTaskStats(): Promise<{
    total: number;
    pending: number;
    approved: number;
    rejected: number;
  }> {
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 300));

    const total = this.tasks.length;
    const pending = this.tasks.filter(task => task.status === 'PENDING_REVIEW').length;
    const approved = this.tasks.filter(task => task.status === 'APPROVED').length;
    const rejected = this.tasks.filter(task => task.status === 'REJECTED').length;

    return { total, pending, approved, rejected };
  }
}

export const humanApprovalDataSource = new HumanApprovalDataSourceImpl();