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

export interface AISuggestion {
  id: string;
  type: string;
  title: string;
  description: string;
  confidence: number;
  priority: 'low' | 'medium' | 'high' | 'urgent';
  status?: 'pending' | 'approved' | 'rejected';
  dataSources: string[];
  reasoning: string[];
  expectedImpact: {
    metric: string;
    value: number;
    unit: string;
    direction: 'positive' | 'negative' | 'neutral';
  };
  alternatives?: {
    id: string;
    title: string;
    description: string;
    confidence: number;
    expectedImpact: {
      metric: string;
      value: number;
      unit: string;
      direction: 'positive' | 'negative' | 'neutral';
    };
  }[];
  supportingData?: {
    id: string;
    title: string;
    type: 'chart' | 'table' | 'text';
    data: any;
  }[];
  createdAt: string;
  updatedAt: string;
}

export interface AISuggestionQueryParams {
  type?: string;
  priority?: string;
  search?: string;
  page?: number;
  pageSize?: number;
}

export interface AISuggestionDataSource {
  fetchSuggestions(params?: AISuggestionQueryParams): Promise<AISuggestion[]>;
  getSuggestion(id: string): Promise<AISuggestion | null>;
  createSuggestion(suggestion: Omit<AISuggestion, 'id' | 'createdAt' | 'updatedAt'>): Promise<AISuggestion>;
  updateSuggestion(id: string, suggestion: Partial<AISuggestion>): Promise<AISuggestion | null>;
  approveSuggestion(id: string): Promise<AISuggestion | null>;
  rejectSuggestion(id: string): Promise<AISuggestion | null>;
  getSuggestionStats(): Promise<{
    total: number;
    byType: Record<string, number>;
    byPriority: Record<string, number>;
    avgConfidence: number;
  }>;
}

export class AISuggestionDataSourceImpl implements AISuggestionDataSource {
  async fetchSuggestions(params?: AISuggestionQueryParams): Promise<AISuggestion[]> {
    const mockSuggestions: AISuggestion[] = [
      {
        id: '1',
        type: 'Pricing Optimization',
        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%.',
        confidence: 85,
        priority: 'high',
        dataSources: ['Competitor Pricing API', 'Sales History', 'Market Trends'],
        reasoning: [
          'Competitor A is selling the same model for $949',
          'Sales volume has decreased by 10% in the last month',
          'Price sensitivity analysis shows a 15% increase in sales with a 5% price decrease',
          'Margins remain above 20% at the suggested price',
        ],
        expectedImpact: {
          metric: 'Sales Volume',
          value: 15,
          unit: '%',
          direction: 'positive',
        },
        alternatives: [
          {
            id: 'alt1',
            title: 'Keep current price',
            description: 'Maintain the current price of $999 to preserve margins.',
            confidence: 60,
            expectedImpact: {
              metric: 'Margins',
              value: 5,
              unit: '%',
              direction: 'positive',
            },
          },
          {
            id: 'alt2',
            title: 'Decrease price to $899',
            description: 'Significantly reduce price to $899 to gain market share.',
            confidence: 70,
            expectedImpact: {
              metric: 'Market Share',
              value: 25,
              unit: '%',
              direction: 'positive',
            },
          },
        ],
        supportingData: [
          {
            id: 'data1',
            title: 'Competitor Pricing',
            type: 'table',
            data: [
              { key: '1', metric: 'Competitor A', value: 949, unit: '$' },
              { key: '2', metric: 'Competitor B', value: 979, unit: '$' },
              { key: '3', metric: 'Competitor C', value: 999, unit: '$' },
              { key: '4', metric: 'Our Price', value: 999, unit: '$' },
            ],
          },
          {
            id: 'data2',
            title: 'Sales Trend',
            type: 'chart',
            data: [
              { month: 'Jan', sales: 100 },
              { month: 'Feb', sales: 95 },
              { month: 'Mar', sales: 90 },
              { month: 'Apr', sales: 85 },
              { month: 'May', sales: 80 },
            ],
          },
        ],
        createdAt: '2026-03-18 10:00:00',
        updatedAt: '2026-03-18 10:30:00',
      },
      {
        id: '2',
        type: 'Inventory Management',
        title: 'Restock iPhone 14 Pro Max',
        description: 'Based on sales velocity and lead time, we recommend restocking 500 units of iPhone 14 Pro Max to avoid stockouts.',
        confidence: 90,
        priority: 'urgent',
        dataSources: ['Inventory API', 'Sales History', 'Lead Time Data'],
        reasoning: [
          'Current stock level is 50 units',
          'Average daily sales is 25 units',
          'Lead time from supplier is 14 days',
          'Safety stock requirement is 100 units',
        ],
        expectedImpact: {
          metric: 'Stockout Risk',
          value: 95,
          unit: '%',
          direction: 'negative',
        },
        supportingData: [
          {
            id: 'data1',
            title: 'Inventory Status',
            type: 'text',
            data: 'Current Stock: 50 units\nReorder Point: 350 units\nSafety Stock: 100 units\nLead Time: 14 days\nAverage Daily Sales: 25 units',
          },
        ],
        createdAt: '2026-03-18 09:00:00',
        updatedAt: '2026-03-18 09:00:00',
      },
      {
        id: '3',
        type: 'Marketing Campaign',
        title: 'Launch summer sale campaign',
        description: 'Based on seasonality and customer behavior, we recommend launching a summer sale campaign with 15% discount on selected items.',
        confidence: 75,
        priority: 'medium',
        dataSources: ['Customer Behavior Data', 'Seasonal Trends', 'Campaign History'],
        reasoning: [
          'Summer is historically a high sales period',
          'Customer engagement increases by 20% during sales',
          'Similar campaigns in the past have generated 30% increase in revenue',
          'Competitors are planning summer promotions',
        ],
        expectedImpact: {
          metric: 'Revenue',
          value: 30,
          unit: '%',
          direction: 'positive',
        },
        createdAt: '2026-03-18 08:00:00',
        updatedAt: '2026-03-18 08:30:00',
      },
    ];

    let filtered = mockSuggestions;

    if (params?.type) {
      filtered = filtered.filter(s => s.type === params.type);
    }

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

    if (params?.search) {
      const searchLower = params.search.toLowerCase();
      filtered = filtered.filter(s => 
        s.title.toLowerCase().includes(searchLower) ||
        s.description.toLowerCase().includes(searchLower)
      );
    }

    return filtered;
  }

  async getSuggestion(id: string): Promise<AISuggestion | null> {
    const suggestions = await this.fetchSuggestions();
    return suggestions.find(s => s.id === id) || null;
  }

  async createSuggestion(suggestion: Omit<AISuggestion, 'id' | 'createdAt' | 'updatedAt'>): Promise<AISuggestion> {
    return {
      ...suggestion,
      id: `suggestion_${Date.now()}`,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
  }

  async updateSuggestion(id: string, suggestion: Partial<AISuggestion>): Promise<AISuggestion | null> {
    const existing = await this.getSuggestion(id);
    if (!existing) return null;

    return {
      ...existing,
      ...suggestion,
      updatedAt: new Date().toISOString(),
    };
  }

  async approveSuggestion(id: string): Promise<AISuggestion | null> {
    return this.updateSuggestion(id, { status: 'approved' });
  }

  async rejectSuggestion(id: string): Promise<AISuggestion | null> {
    return this.updateSuggestion(id, { status: 'rejected' });
  }

  async getSuggestionStats(): Promise<{
    total: number;
    byType: Record<string, number>;
    byPriority: Record<string, number>;
    avgConfidence: number;
  }> {
    const suggestions = await this.fetchSuggestions();
    const byType: Record<string, number> = {};
    const byPriority: Record<string, number> = {};
    let totalConfidence = 0;

    suggestions.forEach(s => {
      byType[s.type] = (byType[s.type] || 0) + 1;
      byPriority[s.priority] = (byPriority[s.priority] || 0) + 1;
      totalConfidence += s.confidence;
    });

    return {
      total: suggestions.length,
      byType,
      byPriority,
      avgConfidence: suggestions.length > 0 ? totalConfidence / suggestions.length : 0,
    };
  }
}

export const aiSuggestionDataSource = new AISuggestionDataSourceImpl();