import { Logger } from '../utils/Logger';
import { PlatformAdapter, TikTokAdapter, TemuAdapter, ShopeeAdapter } from '../platforms';

interface OrderData {
  orderId: string;
  platform: string;
  shopId: string;
  status: string;
  totalAmount: number;
  currency: string;
  items: OrderItem[];
  customerInfo: CustomerInfo;
  createdAt: string;
  updatedAt: string;
  traceId: string;
}

interface OrderItem {
  productId: string;
  skuId: string;
  name: string;
  quantity: number;
  unitPrice: number;
}

interface CustomerInfo {
  name: string;
  phone?: string;
  address?: string;
}

interface SyncResult {
  shopId: string;
  platform: string;
  ordersCollected: number;
  errors: string[];
  traceId: string;
}

export class OrderCollector {
  private logger = new Logger('OrderCollector');
  private platformAdapters: Map<string, PlatformAdapter> = new Map();
  
  constructor() {
    this.platformAdapters.set('tiktok', new TikTokAdapter());
    this.platformAdapters.set('temu', new TemuAdapter());
    this.platformAdapters.set('shopee', new ShopeeAdapter());
  }
  
  async collectOrders(
    shopId: string,
    platform: string,
    dateRange: { start: Date; end: Date },
    traceId: string
  ): Promise<OrderData[]> {
    this.logger.info('Starting order collection', {
      shopId,
      platform,
      dateRange,
      traceId,
    });
    
    const adapter = this.platformAdapters.get(platform.toLowerCase());
    if (!adapter) {
      throw new Error(`Unsupported platform: ${platform}`);
    }
    
    try {
      const orders = await adapter.fetchOrders(shopId, dateRange, traceId);
      
      this.logger.info('Orders collected', {
        shopId,
        platform,
        count: orders.length,
        traceId,
      });
      
      return orders;
    } catch (error: any) {
      this.logger.error('Order collection failed', {
        shopId,
        platform,
        error: error.message,
        traceId,
      });
      throw error;
    }
  }
  
  async syncAllShops(): Promise<SyncResult[]> {
    this.logger.info('Starting sync for all shops');
    
    const shops = await this.getRegisteredShops();
    const results: SyncResult[] = [];
    
    for (const shop of shops) {
      const traceId = this.generateTraceId();
      
      try {
        const dateRange = this.getDefaultDateRange();
        const orders = await this.collectOrders(
          shop.shopId,
          shop.platform,
          dateRange,
          traceId
        );
        
        await this.uploadOrders(orders, shop.tenantId, traceId);
        
        results.push({
          shopId: shop.shopId,
          platform: shop.platform,
          ordersCollected: orders.length,
          errors: [],
          traceId,
        });
      } catch (error: any) {
        results.push({
          shopId: shop.shopId,
          platform: shop.platform,
          ordersCollected: 0,
          errors: [error.message],
          traceId,
        });
      }
    }
    
    this.logger.info('Sync completed for all shops', {
      totalShops: shops.length,
      successCount: results.filter(r => r.errors.length === 0).length,
    });
    
    return results;
  }
  
  private async getRegisteredShops(): Promise<Array<{
    shopId: string;
    platform: string;
    tenantId: string;
  }>> {
    const data = await chrome.storage.local.get('shops');
    return data.shops || [];
  }
  
  private getDefaultDateRange(): { start: Date; end: Date } {
    const end = new Date();
    const start = new Date(end.getTime() - 7 * 24 * 60 * 60 * 1000);
    return { start, end };
  }
  
  private async uploadOrders(
    orders: OrderData[],
    tenantId: string,
    traceId: string
  ): Promise<void> {
    const config = await chrome.storage.local.get('config');
    const apiEndpoint = config.config?.apiEndpoint || 'http://localhost:3003';
    
    const response = await fetch(`${apiEndpoint}/api/orders/batch`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Tenant-Id': tenantId,
        'X-Trace-Id': traceId,
      },
      body: JSON.stringify({
        orders,
        tenantId,
        traceId,
        businessType: 'TOC',
      }),
    });
    
    if (!response.ok) {
      throw new Error(`Upload failed: ${response.status}`);
    }
    
    this.logger.info('Orders uploaded', {
      count: orders.length,
      tenantId,
      traceId,
    });
  }
  
  private generateTraceId(): string {
    return `TRC-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  }
}
