import { http } from './http';
/**
 * [MOCK-CROSS-BORDER] Cross Border Integration DataSource
 */

export interface PlatformIntegration {
  id: string;
  platform: 'sellbrite' | 'shoplazza' | 'salesmartly' | 'amazon' | 'ebay' | 'shopify';
  credentials: Record<string, any>;
  status: 'connected' | 'disconnected' | 'error';
  lastSyncAt?: string;
}

export interface InventorySyncRecord {
  id: string;
  productId: string;
  platform: string;
  platformSku: string;
  quantity: number;
  syncStatus: 'success' | 'failed' | 'pending';
  syncError?: string;
  syncedAt: string;
}

export interface MarketingIntegration {
  id: string;
  platform: string;
  campaignId: string;
  config: Record<string, any>;
  metrics: Record<string, any>;
}

export interface ICrossBorderIntegrationDataSource {
  integrateSellbrite(credentials: { apiKey: string; accountId: string }): Promise<PlatformIntegration>;
  integrateShoplazza(credentials: { apiKey: string; storeId: string }): Promise<PlatformIntegration>;
  integrateSaleSmartly(credentials: { apiKey: string; workspaceId: string }): Promise<PlatformIntegration>;
  syncInventory(inventoryData: Array<{ productId: string; sku: string; quantity: number }>): Promise<InventorySyncRecord[]>;
  integrateMarketing(params: { platform: string; campaignId: string; config: Record<string, any> }): Promise<MarketingIntegration>;
  getIntegrationStatus(platform?: string): Promise<PlatformIntegration[]>;
  disconnectPlatform(platform: string): Promise<{ success: boolean; message: string }>;
}

class MockCrossBorderIntegrationDataSource implements ICrossBorderIntegrationDataSource {
  private integrations: Map<string, PlatformIntegration> = new Map();

  async integrateSellbrite(credentials: { apiKey: string; accountId: string }): Promise<PlatformIntegration> {
    const integration: PlatformIntegration = {
      id: `int_sellbrite_${Date.now()}`,
      platform: 'sellbrite',
      credentials,
      status: 'connected',
      lastSyncAt: new Date().toISOString(),
    };
    this.integrations.set('sellbrite', integration);
    return integration;
  }

  async integrateShoplazza(credentials: { apiKey: string; storeId: string }): Promise<PlatformIntegration> {
    const integration: PlatformIntegration = {
      id: `int_shoplazza_${Date.now()}`,
      platform: 'shoplazza',
      credentials,
      status: 'connected',
      lastSyncAt: new Date().toISOString(),
    };
    this.integrations.set('shoplazza', integration);
    return integration;
  }

  async integrateSaleSmartly(credentials: { apiKey: string; workspaceId: string }): Promise<PlatformIntegration> {
    const integration: PlatformIntegration = {
      id: `int_salesmartly_${Date.now()}`,
      platform: 'salesmartly',
      credentials,
      status: 'connected',
      lastSyncAt: new Date().toISOString(),
    };
    this.integrations.set('salesmartly', integration);
    return integration;
  }

  async syncInventory(inventoryData: Array<{ productId: string; sku: string; quantity: number }>): Promise<InventorySyncRecord[]> {
    return inventoryData.map((item) => ({
      id: `sync_${Date.now()}_${item.productId}`,
      productId: item.productId,
      platform: 'amazon',
      platformSku: item.sku,
      quantity: item.quantity,
      syncStatus: 'success' as const,
      syncedAt: new Date().toISOString(),
    }));
  }

  async integrateMarketing(params: { platform: string; campaignId: string; config: Record<string, any> }): Promise<MarketingIntegration> {
    return {
      id: `mkt_${Date.now()}`,
      platform: params.platform,
      campaignId: params.campaignId,
      config: params.config,
      metrics: {},
    };
  }

  async getIntegrationStatus(platform?: string): Promise<PlatformIntegration[]> {
    if (platform) {
      const integration = this.integrations.get(platform);
      return integration ? [integration] : [];
    }
    return Array.from(this.integrations.values());
  }

  async disconnectPlatform(platform: string): Promise<{ success: boolean; message: string }> {
    const integration = this.integrations.get(platform);
    if (integration) {
      integration.status = 'disconnected';
      return { success: true, message: `Platform ${platform} disconnected` };
    }
    return { success: false, message: `Platform ${platform} not found` };
  }
}

class ApiCrossBorderIntegrationDataSource implements ICrossBorderIntegrationDataSource {
  private baseUrl = '/api/omnichannel';

  async integrateSellbrite(credentials: { apiKey: string; accountId: string }): Promise<PlatformIntegration> {
    const res = await http.post(`${this.baseUrl}/cross-border/sellbrite`, { credentials });
    return res.data;
  }

  async integrateShoplazza(credentials: { apiKey: string; storeId: string }): Promise<PlatformIntegration> {
    const res = await http.post(`${this.baseUrl}/cross-border/shoplazza`, { credentials });
    return res.data;
  }

  async integrateSaleSmartly(credentials: { apiKey: string; workspaceId: string }): Promise<PlatformIntegration> {
    const res = await http.post(`${this.baseUrl}/cross-border/salesmartly`, { credentials });
    return res.data;
  }

  async syncInventory(inventoryData: Array<{ productId: string; sku: string; quantity: number }>): Promise<InventorySyncRecord[]> {
    const res = await http.post(`${this.baseUrl}/cross-border/inventory/sync`, { inventoryData });
    return res.data;
  }

  async integrateMarketing(params: { platform: string; campaignId: string; config: Record<string, any> }): Promise<MarketingIntegration> {
    const res = await http.post(`${this.baseUrl}/cross-border/marketing`, params);
    return res.data;
  }

  async getIntegrationStatus(platform?: string): Promise<PlatformIntegration[]> {
    const query = platform ? `?platform=${platform}` : '';
    const res = await http.get(`${this.baseUrl}/cross-border/integration${query}`);
    return res.data;
  }

  async disconnectPlatform(platform: string): Promise<{ success: boolean; message: string }> {
    const res = await http.delete(`${this.baseUrl}/cross-border/integration/${platform}`);
    return res.data;
  }
}

const useMock = process.env.NODE_ENV === 'development' || process.env.REACT_APP_USE_MOCK === 'true';
export const crossBorderIntegrationDataSource: ICrossBorderIntegrationDataSource = useMock
  ? new MockCrossBorderIntegrationDataSource()
  : new ApiCrossBorderIntegrationDataSource();
