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

import { http } from './http';
import {
  mockProductSelections,
  mockProductSelectionDetail,
  mockCreateProductSelection,
  mockUpdateProductSelection,
  mockDeleteProductSelection,
  ProductPool,
  SelectionRule,
  ListingTask,
  AutoListingConfig,
} from '@/mock/data/productSelection.mock';

const MOCK_CATEGORIES = ['electronics', 'home', 'fashion', 'beauty'];
const MOCK_PLATFORMS = ['Amazon', 'eBay', 'Shopee', 'Lazada'];

const mockProductPool: ProductPool[] = [
  {
    id: '1',
    name: 'Product 1',
    category: 'electronics',
    platform: 'AMAZON',
    roi: 25,
    competition_level: 'LOW',
    trend: 'UP',
    selection_score: 90
  },
  {
    id: '2',
    name: 'Product 2',
    category: 'home',
    platform: 'EBAY',
    roi: 15,
    competition_level: 'MEDIUM',
    trend: 'STABLE',
    selection_score: 75
  },
  {
    id: '3',
    name: 'Product 3',
    category: 'fashion',
    platform: 'AMAZON',
    roi: 30,
    competition_level: 'HIGH',
    trend: 'UP',
    selection_score: 85
  },
  {
    id: '4',
    name: 'Product 4',
    category: 'beauty',
    platform: 'EBAY',
    roi: 20,
    competition_level: 'LOW',
    trend: 'DOWN',
    selection_score: 65
  },
  {
    id: '5',
    name: 'Product 5',
    category: 'electronics',
    platform: 'AMAZON',
    roi: 35,
    competition_level: 'MEDIUM',
    trend: 'UP',
    selection_score: 95
  },
];

const mockSelectionRules: SelectionRule[] = [
  { id: '1', name: 'Rule 1', description: 'High ROI products', criteria: { minROI: 20 }, enabled: true, selected_count: 10 },
  { id: '2', name: 'Rule 2', description: 'Low competition products', criteria: { maxCompetition: 'MEDIUM' }, enabled: false, selected_count: 5 },
  { id: '3', name: 'Rule 3', description: 'Trending products', criteria: { trend: 'UP' }, enabled: true, selected_count: 15 },
];

const mockListingTasks: ListingTask[] = [
  { id: '1', product_id: '1', status: 'PENDING', progress: 0, created_at: '2026-03-18', updated_at: '2026-03-18' },
  { id: '2', product_id: '2', status: 'PROCESSING', progress: 50, created_at: '2026-03-18', updated_at: '2026-03-18' },
  { id: '3', product_id: '3', status: 'COMPLETED', progress: 100, created_at: '2026-03-18', updated_at: '2026-03-18' },
  { id: '4', product_id: '4', status: 'FAILED', progress: 0, created_at: '2026-03-18', updated_at: '2026-03-18' },
];

const mockAutoListingConfig: AutoListingConfig = { 
  enabled: false, 
  max_tasks_per_day: 10, 
  min_roi: 15, 
  max_competition: 'MEDIUM', 
  categories: ['electronics', 'home'] 
};

const getMockProductPool = (params?: ProductPoolQueryParams): ProductPool[] => {
  return mockProductPool;
};

const getMockSelectionRules = (enabled?: boolean): SelectionRule[] => {
  return enabled !== undefined ? mockSelectionRules.filter(rule => rule.enabled === enabled) : mockSelectionRules;
};

const getMockListingTasks = (status?: string): ListingTask[] => {
  return status ? mockListingTasks.filter(task => task.status === status) : mockListingTasks;
};

const createMockSelectionRule = (data: Partial<SelectionRule>): SelectionRule => {
  const newRule: SelectionRule = {
    id: `rule-${Date.now()}`,
    name: data.name || 'New Rule',
    description: data.description || '',
    criteria: data.criteria || {},
    enabled: data.enabled ?? true,
    selected_count: 0,
  };
  mockSelectionRules.push(newRule);
  return newRule;
};

const updateMockSelectionRule = (id: string, data: Partial<SelectionRule>): SelectionRule | null => {
  const index = mockSelectionRules.findIndex(rule => rule.id === id);
  if (index === -1) return null;
  mockSelectionRules[index] = { ...mockSelectionRules[index], ...data };
  return mockSelectionRules[index];
};

const deleteMockSelectionRule = (id: string): boolean => {
  const index = mockSelectionRules.findIndex(rule => rule.id === id);
  if (index === -1) return false;
  mockSelectionRules.splice(index, 1);
  return true;
};

const createMockListingTask = (data: Partial<ListingTask>): ListingTask => {
  const newTask: ListingTask = {
    id: `task-${Date.now()}`,
    product_id: data.product_id || '',
    status: data.status || 'PENDING',
    progress: data.progress || 0,
    created_at: new Date().toISOString(),
    updated_at: new Date().toISOString(),
  };
  mockListingTasks.push(newTask);
  return newTask;
};

const updateMockListingTask = (id: string, data: Partial<ListingTask>): ListingTask | null => {
  const index = mockListingTasks.findIndex(task => task.id === id);
  if (index === -1) return null;
  mockListingTasks[index] = { ...mockListingTasks[index], ...data };
  return mockListingTasks[index];
};

const deleteMockListingTask = (id: string): boolean => {
  const index = mockListingTasks.findIndex(task => task.id === id);
  if (index === -1) return false;
  mockListingTasks.splice(index, 1);
  return true;
};

const getMockAutoListingConfig = (): AutoListingConfig => {
  return mockAutoListingConfig;
};

const updateMockAutoListingConfig = (data: Partial<AutoListingConfig>): AutoListingConfig => {
  Object.assign(mockAutoListingConfig, data);
  return mockAutoListingConfig;
};

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 http.get(`${this.baseUrl}/pool?${query.toString()}`);
    
    const result = response;
    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 http.post(`${this.baseUrl}/rules?${query.toString()}`);
    
    const result = response;
    return result.data || [];
  }

  async createSelectionRule(data: Partial<SelectionRule>): Promise<SelectionRule> {
    const response = await http.post(`${this.baseUrl}/rules`, data);
    
    const result = response;
    return result.data;
  }

  async updateSelectionRule(id: string, data: Partial<SelectionRule>): Promise<SelectionRule> {
    const response = await http.put(`${this.baseUrl}/rules/${id}`, data);
    
    const result = response;
    return result.data;
  }

  async deleteSelectionRule(id: string): Promise<void> {
    const response = await http.delete(`${this.baseUrl}/rules/${id}`);
    
  }

  async toggleSelectionRule(id: string): Promise<SelectionRule> {
    const response = await http.post(`${this.baseUrl}/rules/${id}/toggle`, { method: 'PUT' });
    
    const result = response;
    return result.data;
  }

  async executeSelectionRule(id: string): Promise<{ count: number }> {
    const response = await http.post(`${this.baseUrl}/rules/${id}/execute`);
    
    const result = response;
    return result.data;
  }

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

    const response = await http.post(`${this.baseUrl}/tasks?${query.toString()}`);
    
    const result = response;
    return result.data || [];
  }

  async createListingTask(data: Partial<ListingTask>): Promise<ListingTask> {
    const response = await http.post(`${this.baseUrl}/tasks`, data);
    
    const result = response;
    return result.data;
  }

  async deleteListingTask(id: string): Promise<void> {
    const response = await http.put(`${this.baseUrl}/tasks/${id}`);
    
  }

  async retryListingTask(id: string): Promise<ListingTask> {
    const response = await http.post(`${this.baseUrl}/tasks/${id}/retry`);
    
    const result = response;
    return result.data;
  }

  async getAutoListingConfig(): Promise<AutoListingConfig> {
    const response = await http.get(`${this.baseUrl}/config`);
    
    const result = response;
    return result.data;
  }

  async updateAutoListingConfig(data: Partial<AutoListingConfig>): Promise<AutoListingConfig> {
    const response = await http.post(`${this.baseUrl}/config`, data);
    
    const result = response;
    return result.data;
  }

  async toggleAutoListing(): Promise<boolean> {
    const response = await http.post(`${this.baseUrl}/config/toggle`, { method: 'PUT' });
    
    const result = response;
    return result.data.enabled;
  }

  async getCategories(): Promise<string[]> {
    const response = await http.get(`${this.baseUrl}/categories`);
    
    const result = response;
    return result.data || [];
  }

  async getPlatforms(): Promise<string[]> {
    const response = await http.get(`${this.baseUrl}/platforms`);
    
    const result = response;
    return result.data || [];
  }

  async getSelectionStats(): Promise<{
    totalPool: number;
    totalSelected: number;
    avgROI: number;
    avgScore: number;
    lowCompetition: number;
    upTrend: number;
  }> {
    const response = await http.get(`${this.baseUrl}/stats`);
    
    const result = response;
    return result.data;
  }

  async getListingStats(): Promise<{
    totalTasks: number;
    pendingTasks: number;
    processingTasks: number;
    completedTasks: number;
    failedTasks: number;
  }> {
    const response = await http.get(`${this.baseUrl}/tasks/stats`);
    
    const result = response;
    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: SelectionRule) => 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: SelectionRule) => 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: ProductPool) => p.selected_at).length,
      avgROI: pool.reduce((sum: number, p: ProductPool) => sum + p.roi, 0) / pool.length,
      avgScore: pool.reduce((sum: number, p: ProductPool) => sum + p.selection_score, 0) / pool.length,
      lowCompetition: pool.filter((p: ProductPool) => p.competition_level === 'LOW').length,
      upTrend: pool.filter((p: ProductPool) => 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: ListingTask) => t.status === 'PENDING').length,
      processingTasks: tasks.filter((t: ListingTask) => t.status === 'PROCESSING').length,
      completedTasks: tasks.filter((t: ListingTask) => t.status === 'COMPLETED').length,
      failedTasks: tasks.filter((t: ListingTask) => t.status === 'FAILED').length,
    };
  }
}

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

const useMock = process.env.NODE_ENV === 'development' || 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';
