/**
 * [MOCK] A/B测试数据源
 * AI注意: 这是Mock实现，不是真实业务逻辑
 * 仅在USE_MOCK=true时启用
 */

export interface TestVariant {
  id: string;
  name: string;
  description: string;
  trafficAllocation: number;
  configuration: Record<string, any>;
}

export interface ABTestConfig {
  id: string;
  name: string;
  description: string;
  type: 'UI' | 'PRICE' | 'CONTENT' | 'FEATURE';
  targetMetric: string;
  variants: TestVariant[];
  trafficPercentage: number;
  duration: number;
  startDate: string;
  endDate?: string;
  status: 'DRAFT' | 'RUNNING' | 'PAUSED' | 'COMPLETED' | 'CANCELLED';
  createdAt: string;
  updatedAt: string;
}

export interface ABTestResult {
  id: string;
  testId: string;
  testName: string;
  variantId: string;
  variantName: string;
  impressions: number;
  clicks: number;
  conversions: number;
  revenue: number;
  ctr: number;
  cvr: number;
  revenuePerVisitor: number;
  confidence: number;
  isWinner: boolean;
  startDate: string;
  endDate: string;
}

export interface IABTestDataSource {
  fetchTests(params?: { status?: string; type?: string }): Promise<ABTestConfig[]>;
  createTest(data: Partial<ABTestConfig>): Promise<ABTestConfig>;
  updateTest(id: string, data: Partial<ABTestConfig>): Promise<ABTestConfig>;
  deleteTest(id: string): Promise<void>;
  startTest(id: string): Promise<ABTestConfig>;
  stopTest(id: string): Promise<ABTestConfig>;
  
  fetchTestResults(testId: string): Promise<ABTestResult[]>;
  fetchAllResults(params?: { status?: string }): Promise<ABTestResult[]>;
}

class MockABTestDataSource implements IABTestDataSource {
  private tests: ABTestConfig[] = [
    {
      id: '1',
      name: 'Product Page CTA Test',
      description: 'Testing different CTA button colors',
      type: 'UI',
      targetMetric: 'conversion_rate',
      variants: [
        { id: 'A', name: 'Control', description: 'Blue button', trafficAllocation: 50, configuration: { color: 'blue' } },
        { id: 'B', name: 'Variant', description: 'Green button', trafficAllocation: 50, configuration: { color: 'green' } },
      ],
      trafficPercentage: 100,
      duration: 14,
      startDate: '2026-03-01',
      status: 'RUNNING',
      createdAt: '2026-03-01',
      updatedAt: '2026-03-01',
    },
  ];

  private results: ABTestResult[] = [
    {
      id: '1',
      testId: '1',
      testName: 'Product Page CTA Test',
      variantId: 'A',
      variantName: 'Control',
      impressions: 5000,
      clicks: 250,
      conversions: 50,
      revenue: 5000,
      ctr: 5.0,
      cvr: 20.0,
      revenuePerVisitor: 1.0,
      confidence: 85,
      isWinner: false,
      startDate: '2026-03-01',
      endDate: '2026-03-15',
    },
    {
      id: '2',
      testId: '1',
      testName: 'Product Page CTA Test',
      variantId: 'B',
      variantName: 'Variant',
      impressions: 5000,
      clicks: 300,
      conversions: 75,
      revenue: 7500,
      ctr: 6.0,
      cvr: 25.0,
      revenuePerVisitor: 1.5,
      confidence: 95,
      isWinner: true,
      startDate: '2026-03-01',
      endDate: '2026-03-15',
    },
  ];

  async fetchTests(params?: { status?: string; type?: string }): Promise<ABTestConfig[]> {
    await new Promise(resolve => setTimeout(resolve, 300));
    let result = [...this.tests];
    if (params?.status) {
      result = result.filter(t => t.status === params.status);
    }
    if (params?.type) {
      result = result.filter(t => t.type === params.type);
    }
    return result;
  }

  async createTest(data: Partial<ABTestConfig>): Promise<ABTestConfig> {
    await new Promise(resolve => setTimeout(resolve, 300));
    const newTest: ABTestConfig = {
      id: `${Date.now()}`,
      name: data.name || '',
      description: data.description || '',
      type: data.type || 'UI',
      targetMetric: data.targetMetric || '',
      variants: data.variants || [],
      trafficPercentage: data.trafficPercentage || 100,
      duration: data.duration || 7,
      startDate: data.startDate || new Date().toISOString().split('T')[0],
      status: 'DRAFT',
      createdAt: new Date().toISOString().split('T')[0],
      updatedAt: new Date().toISOString().split('T')[0],
      ...data,
    };
    this.tests.push(newTest);
    return newTest;
  }

  async updateTest(id: string, data: Partial<ABTestConfig>): Promise<ABTestConfig> {
    await new Promise(resolve => setTimeout(resolve, 300));
    const index = this.tests.findIndex(t => t.id === id);
    if (index === -1) throw new Error('Test not found');
    this.tests[index] = { ...this.tests[index], ...data, updatedAt: new Date().toISOString().split('T')[0] };
    return this.tests[index];
  }

  async deleteTest(id: string): Promise<void> {
    await new Promise(resolve => setTimeout(resolve, 300));
    const index = this.tests.findIndex(t => t.id === id);
    if (index !== -1) {
      this.tests.splice(index, 1);
    }
  }

  async startTest(id: string): Promise<ABTestConfig> {
    return this.updateTest(id, { status: 'RUNNING' });
  }

  async stopTest(id: string): Promise<ABTestConfig> {
    return this.updateTest(id, { status: 'COMPLETED' });
  }

  async fetchTestResults(testId: string): Promise<ABTestResult[]> {
    await new Promise(resolve => setTimeout(resolve, 300));
    return this.results.filter(r => r.testId === testId);
  }

  async fetchAllResults(params?: { status?: string }): Promise<ABTestResult[]> {
    await new Promise(resolve => setTimeout(resolve, 300));
    return [...this.results];
  }
}

class ApiABTestDataSource implements IABTestDataSource {
  private baseUrl = '/api/ab-tests';

  async fetchTests(params?: { status?: string; type?: string }): Promise<ABTestConfig[]> {
    const response = await fetch(`${this.baseUrl}?${new URLSearchParams(params as any)}`);
    if (!response.ok) throw new Error('Failed to fetch tests');
    return response.json();
  }

  async createTest(data: Partial<ABTestConfig>): Promise<ABTestConfig> {
    const response = await fetch(this.baseUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });
    if (!response.ok) throw new Error('Failed to create test');
    return response.json();
  }

  async updateTest(id: string, data: Partial<ABTestConfig>): Promise<ABTestConfig> {
    const response = await fetch(`${this.baseUrl}/${id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });
    if (!response.ok) throw new Error('Failed to update test');
    return response.json();
  }

  async deleteTest(id: string): Promise<void> {
    const response = await fetch(`${this.baseUrl}/${id}`, { method: 'DELETE' });
    if (!response.ok) throw new Error('Failed to delete test');
  }

  async startTest(id: string): Promise<ABTestConfig> {
    const response = await fetch(`${this.baseUrl}/${id}/start`, { method: 'POST' });
    if (!response.ok) throw new Error('Failed to start test');
    return response.json();
  }

  async stopTest(id: string): Promise<ABTestConfig> {
    const response = await fetch(`${this.baseUrl}/${id}/stop`, { method: 'POST' });
    if (!response.ok) throw new Error('Failed to stop test');
    return response.json();
  }

  async fetchTestResults(testId: string): Promise<ABTestResult[]> {
    const response = await fetch(`${this.baseUrl}/${testId}/results`);
    if (!response.ok) throw new Error('Failed to fetch test results');
    return response.json();
  }

  async fetchAllResults(params?: { status?: string }): Promise<ABTestResult[]> {
    const response = await fetch(`${this.baseUrl}/results?${new URLSearchParams(params as any)}`);
    if (!response.ok) throw new Error('Failed to fetch all results');
    return response.json();
  }
}

const useMock = process.env.REACT_APP_USE_MOCK === 'true';
export const abTestDataSource: IABTestDataSource = useMock
  ? new MockABTestDataSource()
  : new ApiABTestDataSource();
