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

export interface SKUData {
  id: string;
  tenant_id: string;
  shop_id: string;
  sku_id: string;
  sku_name: string;
  product_name: string;
  return_rate: number;
  return_count: number;
  sales_count: number;
  return_reasons: { reason: string; count: number }[];
  status: 'NORMAL' | 'WARNING' | 'CRITICAL';
  createdAt: string;
  updatedAt: string;
}

export interface ReturnData {
  id: string;
  tenant_id: string;
  shop_id: string;
  sku_id: string;
  sku_name: string;
  product_name: string;
  order_id: string;
  return_reason: string;
  return_type: 'REFUND' | 'EXCHANGE' | 'RETURN';
  status: 'PENDING' | 'APPROVED' | 'PROCESSING' | 'COMPLETED' | 'REJECTED';
  amount: number;
  created_at: string;
  updated_at: string;
}

export interface ReturnTrend {
  date: string;
  returnCount: number;
  returnRate: number;
  refundAmount: number;
}

export interface IReturnDataSource {
  fetchSKUData(params?: { status?: string; shop_id?: string }): Promise<SKUData[]>;
  updateSKUStatus(id: string, status: 'NORMAL' | 'WARNING' | 'CRITICAL'): Promise<SKUData>;
  
  fetchReturns(params?: { status?: string; shop_id?: string; sku_id?: string }): Promise<ReturnData[]>;
  processReturn(id: string, action: 'APPROVE' | 'REJECT'): Promise<ReturnData>;
  
  fetchReturnTrends(params?: { start_date?: string; end_date?: string }): Promise<ReturnTrend[]>;
}

class MockReturnDataSource implements IReturnDataSource {
  private skuData: SKUData[] = [
    {
      id: '1',
      tenant_id: 'tenant_001',
      shop_id: 'shop_001',
      sku_id: 'SKU-001',
      sku_name: 'Product A - Blue',
      product_name: 'Product A',
      return_rate: 15.5,
      return_count: 155,
      sales_count: 1000,
      return_reasons: [
        { reason: 'Wrong size', count: 50 },
        { reason: 'Defective', count: 40 },
        { reason: 'Not as described', count: 35 },
        { reason: 'Changed mind', count: 30 },
      ],
      status: 'WARNING',
      createdAt: '2026-03-01',
      updatedAt: '2026-03-15',
    },
    {
      id: '2',
      tenant_id: 'tenant_001',
      shop_id: 'shop_001',
      sku_id: 'SKU-002',
      sku_name: 'Product B - Red',
      product_name: 'Product B',
      return_rate: 5.2,
      return_count: 52,
      sales_count: 1000,
      return_reasons: [
        { reason: 'Changed mind', count: 30 },
        { reason: 'Defective', count: 22 },
      ],
      status: 'NORMAL',
      createdAt: '2026-03-01',
      updatedAt: '2026-03-15',
    },
  ];

  private returns: ReturnData[] = [
    {
      id: '1',
      tenant_id: 'tenant_001',
      shop_id: 'shop_001',
      sku_id: 'SKU-001',
      sku_name: 'Product A - Blue',
      product_name: 'Product A',
      order_id: 'ORD-2026-001',
      return_reason: 'Wrong size',
      return_type: 'EXCHANGE',
      status: 'PENDING',
      amount: 99.99,
      created_at: '2026-03-15',
      updated_at: '2026-03-15',
    },
  ];

  private trends: ReturnTrend[] = [
    { date: '2026-03-10', returnCount: 12, returnRate: 3.5, refundAmount: 1200 },
    { date: '2026-03-11', returnCount: 15, returnRate: 4.2, refundAmount: 1500 },
    { date: '2026-03-12', returnCount: 10, returnRate: 2.8, refundAmount: 1000 },
    { date: '2026-03-13', returnCount: 18, returnRate: 5.1, refundAmount: 1800 },
    { date: '2026-03-14', returnCount: 14, returnRate: 3.9, refundAmount: 1400 },
    { date: '2026-03-15', returnCount: 20, returnRate: 5.6, refundAmount: 2000 },
  ];

  async fetchSKUData(params?: { status?: string; shop_id?: string }): Promise<SKUData[]> {
    await new Promise(resolve => setTimeout(resolve, 300));
    let result = [...this.skuData];
    if (params?.status) {
      result = result.filter(s => s.status === params.status);
    }
    if (params?.shop_id) {
      result = result.filter(s => s.shop_id === params.shop_id);
    }
    return result;
  }

  async updateSKUStatus(id: string, status: 'NORMAL' | 'WARNING' | 'CRITICAL'): Promise<SKUData> {
    await new Promise(resolve => setTimeout(resolve, 300));
    const index = this.skuData.findIndex(s => s.id === id);
    if (index === -1) throw new Error('SKU not found');
    this.skuData[index] = { ...this.skuData[index], status, updatedAt: new Date().toISOString().split('T')[0] };
    return this.skuData[index];
  }

  async fetchReturns(params?: { status?: string; shop_id?: string; sku_id?: string }): Promise<ReturnData[]> {
    await new Promise(resolve => setTimeout(resolve, 300));
    let result = [...this.returns];
    if (params?.status) {
      result = result.filter(r => r.status === params.status);
    }
    if (params?.shop_id) {
      result = result.filter(r => r.shop_id === params.shop_id);
    }
    if (params?.sku_id) {
      result = result.filter(r => r.sku_id === params.sku_id);
    }
    return result;
  }

  async processReturn(id: string, action: 'APPROVE' | 'REJECT'): Promise<ReturnData> {
    await new Promise(resolve => setTimeout(resolve, 300));
    const index = this.returns.findIndex(r => r.id === id);
    if (index === -1) throw new Error('Return not found');
    this.returns[index] = {
      ...this.returns[index],
      status: action === 'APPROVE' ? 'APPROVED' : 'REJECTED',
      updated_at: new Date().toISOString().split('T')[0],
    };
    return this.returns[index];
  }

  async fetchReturnTrends(params?: { start_date?: string; end_date?: string }): Promise<ReturnTrend[]> {
    await new Promise(resolve => setTimeout(resolve, 300));
    return [...this.trends];
  }
}

class ApiReturnDataSource implements IReturnDataSource {
  private baseUrl = '/api/returns';

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

  async updateSKUStatus(id: string, status: 'NORMAL' | 'WARNING' | 'CRITICAL'): Promise<SKUData> {
    const response = await fetch(`${this.baseUrl}/sku/${id}/status`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ status }),
    });
    if (!response.ok) throw new Error('Failed to update SKU status');
    return response.json();
  }

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

  async processReturn(id: string, action: 'APPROVE' | 'REJECT'): Promise<ReturnData> {
    const response = await fetch(`${this.baseUrl}/${id}/process`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action }),
    });
    if (!response.ok) throw new Error('Failed to process return');
    return response.json();
  }

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

const useMock = process.env.REACT_APP_USE_MOCK === 'true';
export const returnDataSource: IReturnDataSource = useMock
  ? new MockReturnDataSource()
  : new ApiReturnDataSource();
