/**
 * [MOCK-010] 自动选品数据源抽象层
 * 通过环境变量自动切换Mock/真实API
 * AI注意: 这是唯一入口，业务代码必须调用此层
 * 
 * @module services/productSelectionDataSource
 * @author AI-Frontend-33
 * @created 2026-03-20
 */

import {
  ProductPool,
  SelectionRule,
  ListingTask,
  AutoListingConfig,
  MOCK_CATEGORIES,
  MOCK_PLATFORMS,
  mockProductPool,
  mockSelectionRules,
  mockListingTasks,
  mockAutoListingConfig,
  getMockProductPool,
  getMockSelectionRules,
  getMockListingTasks,
  createMockSelectionRule,
  updateMockSelectionRule,
  deleteMockSelectionRule,
  createMockListingTask,
  updateMockListingTask,
  deleteMockListingTask,
  getMockAutoListingConfig,
  updateMockAutoListingConfig,
} from '@/mock/data/productSelection.mock';

export interface ProductPoolQueryParams {
  category?: string;
  min_roi?: number;
  max_roi?: number;
  competition_level?: string;
  trend?: string;
  keyword?: string;
  page?: number;
  pageSize?: number;
}

export interface SelectionRuleQueryParams {
  enabled?: boolean;
}

export interface ListingTaskQueryParams {
  status?: string;
}

// ============================================
// 真实API实现
// ============================================

class ApiProductSelectionDataSource {
  private baseUrl = '/api/v1/product-selection';

  async getProductPool(params?: ProductPoolQueryParams): Promise<ProductPool[]> {
    const query = new URLSearchParams();
    if (params?.category) query.append('category', params.category);
    if (params?.min_roi) query.append('min_roi', params.min_roi.toString());
    if (params?.max_roi) query.append('max_roi', params.max_roi.toString());
    if (params?.competition_level) query.append('competition_level', params.competition_level);
    if (params?.trend) query.append('trend', params.trend);
    if (params?.keyword) query.append('keyword', params.keyword);
    if (params?.page) query.append('page', params.page.toString());
    if (params?.pageSize) query.append('pageSize', params.pageSize.toString());

    const response = await fetch(`${this.baseUrl}/pool?${query.toString()}`);
    if (!response.ok) throw new Error(`API Error: ${response.status}`);
    const result = await response.json();
    return result.data || [];
  }

  async getSelectionRules(params?: SelectionRuleQueryParams): Promise<SelectionRule[]> {
    const query = new URLSearchParams();
    if (params?.enabled !== undefined) query.append('enabled', params.enabled.toString());

    const response = await fetch(`${this.baseUrl}/rules?${query.toString()}`);
    if (!response.ok) throw new Error(`API Error: ${response.status}`);
    const result = await response.json();
    return result.data || [];
  }

  async createSelectionRule(data: Partial<SelectionRule>): Promise<SelectionRule> {
    const response = await fetch(`${this.baseUrl}/rules`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });
    if (!response.ok) throw new Error(`API Error: ${response.status}`);
    const result = await response.json();
    return result.data;
  }

  async updateSelectionRule(id: string, data: Partial<SelectionRule>): Promise<SelectionRule> {
    const response = await fetch(`${this.baseUrl}/rules/${id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });
    if (!response.ok) throw new Error(`API Error: ${response.status}`);
    const result = await response.json();
    return result.data;
  }

  async deleteSelectionRule(id: string): Promise<void> {
    const response = await fetch(`${this.baseUrl}/rules/${id}`, { method: 'DELETE' });
    if (!response.ok) throw new Error(`API Error: ${response.status}`);
  }

  async toggleSelectionRule(id: string): Promise<SelectionRule> {
    const response = await fetch(`${this.baseUrl}/rules/${id}/toggle`, { method: 'PUT' });
    if (!response.ok) throw new Error(`API Error: ${response.status}`);
    const result = await response.json();
    return result.data;
  }

  async executeSelectionRule(id: string): Promise<{ count: number }> {
    const response = await fetch(`${this.baseUrl}/rules/${id}/execute`, { method: 'POST' });
    if (!response.ok) throw new Error(`API Error: ${response.status}`);
    const result = await response.json();
    return result.data;
  }

  async getListingTasks(params?: ListingTaskQueryParams): Promise<ListingTask[]> {
    const query = new URLSearchParams();
    if (params?.status) query.append('status', params.status);

    const response = await fetch(`${this.baseUrl}/tasks?${query.toString()}`);
    if (!response.ok) throw new Error(`API Error: ${response.status}`);
    const result = await response.json();
    return result.data || [];
  }

  async createListingTask(data: Partial<ListingTask>): Promise<ListingTask> {
    const response = await fetch(`${this.baseUrl}/tasks`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });
    if (!response.ok) throw new Error(`API Error: ${response.status}`);
    const result = await response.json();
    return result.data;
  }

  async deleteListingTask(id: string): Promise<void> {
    const response = await fetch(`${this.baseUrl}/tasks/${id}`, { method: 'DELETE' });
    if (!response.ok) throw new Error(`API Error: ${response.status}`);
  }

  async retryListingTask(id: string): Promise<ListingTask> {
    const response = await fetch(`${this.baseUrl}/tasks/${id}/retry`, { method: 'POST' });
    if (!response.ok) throw new Error(`API Error: ${response.status}`);
    const result = await response.json();
    return result.data;
  }

  async getAutoListingConfig(): Promise<AutoListingConfig> {
    const response = await fetch(`${this.baseUrl}/config`);
    if (!response.ok) throw new Error(`API Error: ${response.status}`);
    const result = await response.json();
    return result.data;
  }

  async updateAutoListingConfig(data: Partial<AutoListingConfig>): Promise<AutoListingConfig> {
    const response = await fetch(`${this.baseUrl}/config`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });
    if (!response.ok) throw new Error(`API Error: ${response.status}`);
    const result = await response.json();
    return result.data;
  }

  async toggleAutoListing(): Promise<boolean> {
    const response = await fetch(`${this.baseUrl}/config/toggle`, { method: 'PUT' });
    if (!response.ok) throw new Error(`API Error: ${response.status}`);
    const result = await response.json();
    return result.data.enabled;
  }

  async getCategories(): Promise<string[]> {
    const response = await fetch(`${this.baseUrl}/categories`);
    if (!response.ok) throw new Error(`API Error: ${response.status}`);
    const result = await response.json();
    return result.data || [];
  }

  async getPlatforms(): Promise<string[]> {
    const response = await fetch(`${this.baseUrl}/platforms`);
    if (!response.ok) throw new Error(`API Error: ${response.status}`);
    const result = await response.json();
    return result.data || [];
  }

  async getSelectionStats(): Promise<{
    totalPool: number;
    totalSelected: number;
    avgROI: number;
    avgScore: number;
    lowCompetition: number;
    upTrend: number;
  }> {
    const response = await fetch(`${this.baseUrl}/stats`);
    if (!response.ok) throw new Error(`API Error: ${response.status}`);
    const result = await response.json();
    return result.data;
  }

  async getListingStats(): Promise<{
    totalTasks: number;
    pendingTasks: number;
    processingTasks: number;
    completedTasks: number;
    failedTasks: number;
  }> {
    const response = await fetch(`${this.baseUrl}/tasks/stats`);
    if (!response.ok) throw new Error(`API Error: ${response.status}`);
    const result = await response.json();
    return result.data;
  }
}

// ============================================
// Mock实现
// ============================================

class MockProductSelectionDataSource {
  readonly __MOCK__ = true as const;
  readonly __MOCK_NAME__ = 'MockProductSelectionDataSource';

  private delay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  async getProductPool(params?: ProductPoolQueryParams): Promise<ProductPool[]> {
    await this.delay(300);
    return getMockProductPool(params);
  }

  async getSelectionRules(params?: SelectionRuleQueryParams): Promise<SelectionRule[]> {
    await this.delay(200);
    return getMockSelectionRules(params?.enabled);
  }

  async createSelectionRule(data: Partial<SelectionRule>): Promise<SelectionRule> {
    await this.delay(500);
    return createMockSelectionRule(data);
  }

  async updateSelectionRule(id: string, data: Partial<SelectionRule>): Promise<SelectionRule> {
    await this.delay(300);
    const result = updateMockSelectionRule(id, data);
    if (!result) throw new Error('Rule not found');
    return result;
  }

  async deleteSelectionRule(id: string): Promise<void> {
    await this.delay(200);
    deleteMockSelectionRule(id);
  }

  async toggleSelectionRule(id: string): Promise<SelectionRule> {
    await this.delay(200);
    const rule = mockSelectionRules.find(r => r.id === id);
    if (!rule) throw new Error('Rule not found');
    rule.enabled = !rule.enabled;
    return rule;
  }

  async executeSelectionRule(id: string): Promise<{ count: number }> {
    await this.delay(1000);
    const count = Math.floor(Math.random() * 20) + 5;
    const rule = mockSelectionRules.find(r => r.id === id);
    if (rule) {
      rule.selected_count += count;
      rule.last_run_at = new Date().toISOString().replace('T', ' ').slice(0, 19);
    }
    return { count };
  }

  async getListingTasks(params?: ListingTaskQueryParams): Promise<ListingTask[]> {
    await this.delay(200);
    return getMockListingTasks(params?.status);
  }

  async createListingTask(data: Partial<ListingTask>): Promise<ListingTask> {
    await this.delay(500);
    return createMockListingTask(data);
  }

  async deleteListingTask(id: string): Promise<void> {
    await this.delay(200);
    deleteMockListingTask(id);
  }

  async retryListingTask(id: string): Promise<ListingTask> {
    await this.delay(500);
    const result = updateMockListingTask(id, { status: 'PENDING', progress: 0 });
    if (!result) throw new Error('Task not found');
    return result;
  }

  async getAutoListingConfig(): Promise<AutoListingConfig> {
    await this.delay(100);
    return getMockAutoListingConfig();
  }

  async updateAutoListingConfig(data: Partial<AutoListingConfig>): Promise<AutoListingConfig> {
    await this.delay(300);
    return updateMockAutoListingConfig(data);
  }

  async toggleAutoListing(): Promise<boolean> {
    await this.delay(200);
    mockAutoListingConfig.enabled = !mockAutoListingConfig.enabled;
    return mockAutoListingConfig.enabled;
  }

  async getCategories(): Promise<string[]> {
    await this.delay(100);
    return MOCK_CATEGORIES;
  }

  async getPlatforms(): Promise<string[]> {
    await this.delay(100);
    return MOCK_PLATFORMS;
  }

  async getSelectionStats(): Promise<{
    totalPool: number;
    totalSelected: number;
    avgROI: number;
    avgScore: number;
    lowCompetition: number;
    upTrend: number;
  }> {
    await this.delay(200);
    const pool = mockProductPool;
    return {
      totalPool: pool.length,
      totalSelected: pool.filter(p => p.selected_at).length,
      avgROI: pool.reduce((sum, p) => sum + p.roi, 0) / pool.length,
      avgScore: pool.reduce((sum, p) => sum + p.selection_score, 0) / pool.length,
      lowCompetition: pool.filter(p => p.competition_level === 'LOW').length,
      upTrend: pool.filter(p => p.trend === 'UP').length,
    };
  }

  async getListingStats(): Promise<{
    totalTasks: number;
    pendingTasks: number;
    processingTasks: number;
    completedTasks: number;
    failedTasks: number;
  }> {
    await this.delay(200);
    const tasks = mockListingTasks;
    return {
      totalTasks: tasks.length,
      pendingTasks: tasks.filter(t => t.status === 'PENDING').length,
      processingTasks: tasks.filter(t => t.status === 'PROCESSING').length,
      completedTasks: tasks.filter(t => t.status === 'COMPLETED').length,
      failedTasks: tasks.filter(t => t.status === 'FAILED').length,
    };
  }
}

// ============================================
// 导出数据源实例 (环境变量控制)
// ============================================

const useMock = process.env.REACT_APP_USE_MOCK === 'true';

export const productSelectionDataSource = useMock
  ? new MockProductSelectionDataSource()
  : new ApiProductSelectionDataSource();

export const __MOCK__ = useMock;
export const __DATA_SOURCE_TYPE__ = useMock ? 'mock' : 'api';
