/**
 * [MOCK-SETTINGS] Settings模块DataSource
 * AI注意: 这是DataSource抽象层实现
 * 仅在USE_MOCK=true时启用Mock
 */

export interface CostTemplate {
  id: string;
  name: string;
  category: string;
  platform: string;
  costItems: CostItem[];
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
}

export interface CostItem {
  name: string;
  type: 'fixed' | 'percentage';
  value: number;
  currency: string;
}

export interface WinNode {
  id: string;
  name: string;
  platform: string;
  accountId: string;
  profileDir: string;
  proxy: ProxyConfig;
  fingerprintPolicy: FingerprintPolicy;
  status: 'active' | 'inactive' | 'error';
  lastUsed?: string;
  createdAt: string;
}

export interface ProxyConfig {
  host: string;
  port: number;
  username?: string;
  password?: string;
  type: 'http' | 'https' | 'socks5';
}

export interface FingerprintPolicy {
  userAgent: string;
  timezone: string;
  language: string;
  screenResolution: string;
  webgl: string;
}

export interface ExchangeRate {
  id: string;
  fromCurrency: string;
  toCurrency: string;
  rate: number;
  source: string;
  updatedAt: string;
}

export interface PlatformAccount {
  id: string;
  platform: string;
  accountName: string;
  accountId: string;
  status: 'active' | 'inactive' | 'expired';
  token?: string;
  refreshToken?: string;
  expiresAt?: string;
  shopId?: string;
  createdAt: string;
}

export interface SystemSetting {
  key: string;
  value: any;
  category: string;
  description: string;
  updatedAt: string;
}

export interface User {
  id: string;
  username: string;
  email: string;
  role: string;
  status: 'active' | 'inactive' | 'pending';
  parentId?: string;
  createdAt: string;
  lastLoginAt?: string;
}

export interface ISettingsDataSource {
  fetchCostTemplates(): Promise<CostTemplate[]>;
  saveCostTemplate(data: Partial<CostTemplate>): Promise<CostTemplate>;
  deleteCostTemplate(id: string): Promise<void>;
  
  fetchWinNodes(): Promise<WinNode[]>;
  saveWinNode(data: Partial<WinNode>): Promise<WinNode>;
  deleteWinNode(id: string): Promise<void>;
  testWinNode(id: string): Promise<{ success: boolean; message: string }>;
  
  fetchExchangeRates(): Promise<ExchangeRate[]>;
  updateExchangeRate(id: string, rate: number): Promise<ExchangeRate>;
  refreshExchangeRates(): Promise<ExchangeRate[]>;
  
  fetchPlatformAccounts(): Promise<PlatformAccount[]>;
  savePlatformAccount(data: Partial<PlatformAccount>): Promise<PlatformAccount>;
  deletePlatformAccount(id: string): Promise<void>;
  testPlatformAccount(id: string): Promise<{ success: boolean; message: string }>;
  
  fetchSystemSettings(): Promise<SystemSetting[]>;
  updateSystemSetting(key: string, value: any): Promise<SystemSetting>;
  
  fetchUsers(): Promise<User[]>;
  saveUser(data: Partial<User>): Promise<User>;
  deleteUser(id: string): Promise<void>;
}

class MockSettingsDataSource implements ISettingsDataSource {
  async fetchCostTemplates(): Promise<CostTemplate[]> {
    return [
      {
        id: 'ct_001',
        name: 'Amazon US Standard',
        category: 'amazon',
        platform: 'AMAZON_US',
        costItems: [
          { name: 'Platform Fee', type: 'percentage', value: 15, currency: 'USD' },
          { name: 'FBA Fee', type: 'fixed', value: 3.5, currency: 'USD' },
          { name: 'Storage Fee', type: 'fixed', value: 0.5, currency: 'USD' },
        ],
        isActive: true,
        createdAt: '2026-03-01 10:00:00',
        updatedAt: '2026-03-18 14:30:00',
      },
      {
        id: 'ct_002',
        name: 'eBay Standard',
        category: 'ebay',
        platform: 'EBAY',
        costItems: [
          { name: 'Platform Fee', type: 'percentage', value: 12.5, currency: 'USD' },
          { name: 'PayPal Fee', type: 'percentage', value: 2.9, currency: 'USD' },
        ],
        isActive: true,
        createdAt: '2026-03-05 09:00:00',
        updatedAt: '2026-03-15 11:00:00',
      },
    ];
  }

  async saveCostTemplate(data: Partial<CostTemplate>): Promise<CostTemplate> {
    return { ...data, id: data.id || `ct_${Date.now()}`, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() } as CostTemplate;
  }

  async deleteCostTemplate(id: string): Promise<void> {}

  async fetchWinNodes(): Promise<WinNode[]> {
    return [
      {
        id: 'wn_001',
        name: 'US-Shop-01',
        platform: 'AMAZON',
        accountId: 'shop_us_001',
        profileDir: '/profiles/us_shop_01',
        proxy: { host: 'proxy1.example.com', port: 8080, type: 'http' },
        fingerprintPolicy: {
          userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
          timezone: 'America/New_York',
          language: 'en-US',
          screenResolution: '1920x1080',
          webgl: 'NVIDIA GeForce GTX 1080',
        },
        status: 'active',
        lastUsed: '2026-03-18 15:00:00',
        createdAt: '2026-03-01 10:00:00',
      },
      {
        id: 'wn_002',
        name: 'UK-Shop-01',
        platform: 'AMAZON',
        accountId: 'shop_uk_001',
        profileDir: '/profiles/uk_shop_01',
        proxy: { host: 'proxy2.example.com', port: 8080, type: 'https', username: 'user1', password: '***' },
        fingerprintPolicy: {
          userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
          timezone: 'Europe/London',
          language: 'en-GB',
          screenResolution: '1920x1080',
          webgl: 'NVIDIA GeForce GTX 1080',
        },
        status: 'active',
        lastUsed: '2026-03-18 12:00:00',
        createdAt: '2026-03-02 10:00:00',
      },
    ];
  }

  async saveWinNode(data: Partial<WinNode>): Promise<WinNode> {
    return { ...data, id: data.id || `wn_${Date.now()}`, createdAt: new Date().toISOString() } as WinNode;
  }

  async deleteWinNode(id: string): Promise<void> {}
  async testWinNode(id: string): Promise<{ success: boolean; message: string }> {
    return { success: true, message: 'Connection successful' };
  }

  async fetchExchangeRates(): Promise<ExchangeRate[]> {
    return [
      { id: 'er_001', fromCurrency: 'USD', toCurrency: 'CNY', rate: 7.25, source: 'ECB', updatedAt: '2026-03-18 10:00:00' },
      { id: 'er_002', fromCurrency: 'EUR', toCurrency: 'CNY', rate: 7.85, source: 'ECB', updatedAt: '2026-03-18 10:00:00' },
      { id: 'er_003', fromCurrency: 'GBP', toCurrency: 'CNY', rate: 9.15, source: 'ECB', updatedAt: '2026-03-18 10:00:00' },
      { id: 'er_004', fromCurrency: 'JPY', toCurrency: 'CNY', rate: 0.048, source: 'ECB', updatedAt: '2026-03-18 10:00:00' },
    ];
  }

  async updateExchangeRate(id: string, rate: number): Promise<ExchangeRate> {
    return { id, fromCurrency: 'USD', toCurrency: 'CNY', rate, source: 'manual', updatedAt: new Date().toISOString() };
  }

  async refreshExchangeRates(): Promise<ExchangeRate[]> {
    return this.fetchExchangeRates();
  }

  async fetchPlatformAccounts(): Promise<PlatformAccount[]> {
    return [
      { id: 'pa_001', platform: 'AMAZON', accountName: 'US Store', accountId: 'amazon_us_001', status: 'active', shopId: 'shop_001', createdAt: '2026-03-01 10:00:00' },
      { id: 'pa_002', platform: 'EBAY', accountName: 'eBay Main', accountId: 'ebay_main_001', status: 'active', createdAt: '2026-03-05 09:00:00' },
      { id: 'pa_003', platform: 'SHOPIFY', accountName: 'Brand Store', accountId: 'shopify_brand_001', status: 'active', shopId: 'brand-store.myshopify.com', createdAt: '2026-03-10 14:00:00' },
    ];
  }

  async savePlatformAccount(data: Partial<PlatformAccount>): Promise<PlatformAccount> {
    return { ...data, id: data.id || `pa_${Date.now()}`, createdAt: new Date().toISOString() } as PlatformAccount;
  }

  async deletePlatformAccount(id: string): Promise<void> {}
  async testPlatformAccount(id: string): Promise<{ success: boolean; message: string }> {
    return { success: true, message: 'Account connection successful' };
  }

  async fetchSystemSettings(): Promise<SystemSetting[]> {
    return [
      { key: 'default_currency', value: 'USD', category: 'general', description: 'Default currency for pricing', updatedAt: '2026-03-01 10:00:00' },
      { key: 'profit_threshold_b2b', value: 15, category: 'pricing', description: 'Minimum profit margin for B2B', updatedAt: '2026-03-01 10:00:00' },
      { key: 'profit_threshold_b2c', value: 20, category: 'pricing', description: 'Minimum profit margin for B2C', updatedAt: '2026-03-01 10:00:00' },
      { key: 'auto_sync_enabled', value: true, category: 'sync', description: 'Enable automatic inventory sync', updatedAt: '2026-03-01 10:00:00' },
    ];
  }

  async updateSystemSetting(key: string, value: any): Promise<SystemSetting> {
    return { key, value, category: 'general', description: '', updatedAt: new Date().toISOString() };
  }

  async fetchUsers(): Promise<User[]> {
    return [
      { id: 'u_001', username: 'admin', email: 'admin@example.com', role: 'ADMIN', status: 'active', createdAt: '2026-03-01 10:00:00', lastLoginAt: '2026-03-18 15:00:00' },
      { id: 'u_002', username: 'operator1', email: 'operator1@example.com', role: 'OPERATOR', status: 'active', parentId: 'u_001', createdAt: '2026-03-05 09:00:00' },
      { id: 'u_003', username: 'finance1', email: 'finance1@example.com', role: 'FINANCE', status: 'active', parentId: 'u_001', createdAt: '2026-03-10 14:00:00' },
    ];
  }

  async saveUser(data: Partial<User>): Promise<User> {
    return { ...data, id: data.id || `u_${Date.now()}`, createdAt: new Date().toISOString() } as User;
  }

  async deleteUser(id: string): Promise<void> {}
}

class ApiSettingsDataSource implements ISettingsDataSource {
  private baseUrl = '/api/settings';

  async fetchCostTemplates(): Promise<CostTemplate[]> {
    const res = await fetch(`${this.baseUrl}/cost-templates`);
    return res.json();
  }

  async saveCostTemplate(data: Partial<CostTemplate>): Promise<CostTemplate> {
    const res = await fetch(`${this.baseUrl}/cost-templates`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
    return res.json();
  }

  async deleteCostTemplate(id: string): Promise<void> {
    await fetch(`${this.baseUrl}/cost-templates/${id}`, { method: 'DELETE' });
  }

  async fetchWinNodes(): Promise<WinNode[]> {
    const res = await fetch(`${this.baseUrl}/win-nodes`);
    return res.json();
  }

  async saveWinNode(data: Partial<WinNode>): Promise<WinNode> {
    const res = await fetch(`${this.baseUrl}/win-nodes`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
    return res.json();
  }

  async deleteWinNode(id: string): Promise<void> {
    await fetch(`${this.baseUrl}/win-nodes/${id}`, { method: 'DELETE' });
  }

  async testWinNode(id: string): Promise<{ success: boolean; message: string }> {
    const res = await fetch(`${this.baseUrl}/win-nodes/${id}/test`);
    return res.json();
  }

  async fetchExchangeRates(): Promise<ExchangeRate[]> {
    const res = await fetch(`${this.baseUrl}/exchange-rates`);
    return res.json();
  }

  async updateExchangeRate(id: string, rate: number): Promise<ExchangeRate> {
    const res = await fetch(`${this.baseUrl}/exchange-rates/${id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ rate }) });
    return res.json();
  }

  async refreshExchangeRates(): Promise<ExchangeRate[]> {
    const res = await fetch(`${this.baseUrl}/exchange-rates/refresh`, { method: 'POST' });
    return res.json();
  }

  async fetchPlatformAccounts(): Promise<PlatformAccount[]> {
    const res = await fetch(`${this.baseUrl}/platform-accounts`);
    return res.json();
  }

  async savePlatformAccount(data: Partial<PlatformAccount>): Promise<PlatformAccount> {
    const res = await fetch(`${this.baseUrl}/platform-accounts`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
    return res.json();
  }

  async deletePlatformAccount(id: string): Promise<void> {
    await fetch(`${this.baseUrl}/platform-accounts/${id}`, { method: 'DELETE' });
  }

  async testPlatformAccount(id: string): Promise<{ success: boolean; message: string }> {
    const res = await fetch(`${this.baseUrl}/platform-accounts/${id}/test`);
    return res.json();
  }

  async fetchSystemSettings(): Promise<SystemSetting[]> {
    const res = await fetch(`${this.baseUrl}/system`);
    return res.json();
  }

  async updateSystemSetting(key: string, value: any): Promise<SystemSetting> {
    const res = await fetch(`${this.baseUrl}/system/${key}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value }) });
    return res.json();
  }

  async fetchUsers(): Promise<User[]> {
    const res = await fetch(`${this.baseUrl}/users`);
    return res.json();
  }

  async saveUser(data: Partial<User>): Promise<User> {
    const res = await fetch(`${this.baseUrl}/users`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
    return res.json();
  }

  async deleteUser(id: string): Promise<void> {
    await fetch(`${this.baseUrl}/users/${id}`, { method: 'DELETE' });
  }
}

const useMock = process.env.REACT_APP_USE_MOCK === 'true';
export const settingsDataSource: ISettingsDataSource = useMock ? new MockSettingsDataSource() : new ApiSettingsDataSource();
