/**
 * [MOCK-SITE-001] IndependentSite数据源抽象层
 * AI注意: 这是数据源抽象层，业务组件通过此层获取数据
 * 仅在REACT_APP_USE_MOCK=true时启用Mock
 * 
 * @module services/independentSiteDataSource
 * @created 2026-03-19
 */

import { IDataSource, IMockDataSource } from '@/types/datasource';

// ============================================
// 类型定义
// ============================================

export interface SiteSettings {
  inventorySync: boolean;
  orderSync: boolean;
  pricingSync: boolean;
  autoPublish: boolean;
  currency: string;
  language: string;
}

export interface SiteShipping {
  freeShipping: boolean;
  freeShippingThreshold: number;
  shippingZones: string[];
}

export interface SitePayment {
  paypal: boolean;
  stripe: boolean;
  creditCard: boolean;
  applePay: boolean;
}

export interface IndependentSite {
  id: string;
  name: string;
  url: string;
  platform: string;
  apiKey: string;
  apiSecret: string;
  webhookUrl: string;
  theme: string;
  description: string;
  isActive: boolean;
  notes: string;
  settings: SiteSettings;
  shipping: SiteShipping;
  payment: SitePayment;
}

export interface SiteQueryParams {
  keyword?: string;
  platform?: string;
  status?: string;
}

// ============================================
// IndependentSite专用接口
// ============================================

export interface IIndependentSiteDataSource extends IDataSource<IndependentSite, SiteQueryParams> {
  fetchSiteConfig(id: string): Promise<IndependentSite | null>;
  updateSiteConfig(id: string, data: Partial<IndependentSite>): Promise<IndependentSite>;
}

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

class ApiIndependentSiteDataSource implements IIndependentSiteDataSource {
  async list(params?: SiteQueryParams): Promise<IndependentSite[]> {
    const query = new URLSearchParams(params as any).toString();
    const response = await fetch(`/api/v1/sites?${query}`);
    const result = await response.json();
    return result.data;
  }

  async detail(id: string): Promise<IndependentSite | null> {
    return this.fetchSiteConfig(id);
  }

  async fetchSiteConfig(id: string): Promise<IndependentSite | null> {
    const response = await fetch(`/api/v1/sites/${id}`);
    const result = await response.json();
    return result.data;
  }

  async create(data: Partial<IndependentSite>): Promise<IndependentSite> {
    const response = await fetch('/api/v1/sites', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });
    const result = await response.json();
    return result.data;
  }

  async update(id: string, data: Partial<IndependentSite>): Promise<IndependentSite> {
    const response = await fetch(`/api/v1/sites/${id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });
    const result = await response.json();
    return result.data;
  }

  async delete(id: string): Promise<void> {
    await fetch(`/api/v1/sites/${id}`, { method: 'DELETE' });
  }

  async updateSiteConfig(id: string, data: Partial<IndependentSite>): Promise<IndependentSite> {
    return this.update(id, data);
  }
}

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

/**
 * [MOCK] IndependentSite Mock数据源
 * AI注意: 这是Mock实现，不是真实业务逻辑
 * 仅在REACT_APP_USE_MOCK=true时启用
 */
class MockIndependentSiteDataSource implements IIndependentSiteDataSource, IMockDataSource {
  readonly __MOCK__ = true as const;
  readonly __MOCK_NAME__ = 'MockIndependentSiteDataSource';

  private mockSites: IndependentSite[] = [
    {
      id: 'site-001',
      name: 'Test Store 1',
      url: 'https://test-store-1.com',
      platform: 'Shopify',
      apiKey: 'test-api-key',
      apiSecret: 'test-api-secret',
      webhookUrl: 'https://webhook.example.com',
      theme: 'default',
      description: 'Test store for demonstration',
      isActive: true,
      notes: 'This is a test store',
      settings: {
        inventorySync: true,
        orderSync: true,
        pricingSync: true,
        autoPublish: false,
        currency: 'USD',
        language: 'en',
      },
      shipping: {
        freeShipping: true,
        freeShippingThreshold: 50,
        shippingZones: ['US', 'CA', 'EU'],
      },
      payment: {
        paypal: true,
        stripe: true,
        creditCard: true,
        applePay: false,
      },
    },
  ];

  async list(params?: SiteQueryParams): Promise<IndependentSite[]> {
    await this.simulateDelay(300);
    let result = [...this.mockSites];
    if (params?.platform) {
      result = result.filter(s => s.platform === params.platform);
    }
    if (params?.status) {
      const isActive = params.status === 'active';
      result = result.filter(s => s.isActive === isActive);
    }
    return result;
  }

  async detail(id: string): Promise<IndependentSite | null> {
    return this.fetchSiteConfig(id);
  }

  async fetchSiteConfig(id: string): Promise<IndependentSite | null> {
    await this.simulateDelay(500);
    const site = this.mockSites.find(s => s.id === id);
    return site ? { ...site } : null;
  }

  async create(data: Partial<IndependentSite>): Promise<IndependentSite> {
    await this.simulateDelay(500);
    const newSite: IndependentSite = {
      id: `site-${Date.now()}`,
      name: data.name || '',
      url: data.url || '',
      platform: data.platform || 'Shopify',
      apiKey: data.apiKey || '',
      apiSecret: data.apiSecret || '',
      webhookUrl: data.webhookUrl || '',
      theme: data.theme || 'default',
      description: data.description || '',
      isActive: data.isActive ?? true,
      notes: data.notes || '',
      settings: data.settings || {
        inventorySync: true,
        orderSync: true,
        pricingSync: true,
        autoPublish: false,
        currency: 'USD',
        language: 'en',
      },
      shipping: data.shipping || {
        freeShipping: false,
        freeShippingThreshold: 0,
        shippingZones: [],
      },
      payment: data.payment || {
        paypal: false,
        stripe: false,
        creditCard: false,
        applePay: false,
      },
    };
    this.mockSites.push(newSite);
    return newSite;
  }

  async update(id: string, data: Partial<IndependentSite>): Promise<IndependentSite> {
    await this.simulateDelay(300);
    const index = this.mockSites.findIndex(s => s.id === id);
    if (index === -1) throw new Error('Site not found');
    this.mockSites[index] = { ...this.mockSites[index], ...data };
    return this.mockSites[index];
  }

  async delete(id: string): Promise<void> {
    await this.simulateDelay(200);
    this.mockSites = this.mockSites.filter(s => s.id !== id);
  }

  async updateSiteConfig(id: string, data: Partial<IndependentSite>): Promise<IndependentSite> {
    return this.update(id, data);
  }

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

// ============================================
// 导出数据源实例
// ============================================

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

export const independentSiteDataSource: IIndependentSiteDataSource = useMock
  ? new MockIndependentSiteDataSource()
  : new ApiIndependentSiteDataSource();

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