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

interface ReturnData {
  returnId: string;
  orderId: string;
  platform: string;
  shopId: string;
  status: string;
  reason: string;
  items: ReturnItem[];
  refundAmount: number;
  currency: string;
  createdAt: string;
  updatedAt: string;
  traceId: string;
}

interface ReturnItem {
  productId: string;
  skuId: string;
  quantity: number;
  reason?: string;
}

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

export class ReturnSync {
  private logger = new Logger('ReturnSync');
  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 syncReturns(
    shopId: string,
    platform: string,
    returnIds?: string[],
    traceId?: string
  ): Promise<ReturnData[]> {
    const actualTraceId = traceId || this.generateTraceId();
    
    this.logger.info('Starting return sync', {
      shopId,
      platform,
      returnIds,
      traceId: actualTraceId,
    });
    
    const adapter = this.platformAdapters.get(platform.toLowerCase());
    if (!adapter) {
      throw new Error(`Unsupported platform: ${platform}`);
    }
    
    try {
      const returns = await adapter.fetchReturns(shopId, returnIds, actualTraceId);
      
      this.logger.info('Returns synced', {
        shopId,
        platform,
        count: returns.length,
        traceId: actualTraceId,
      });
      
      return returns;
    } catch (error: any) {
      this.logger.error('Return sync failed', {
        shopId,
        platform,
        error: error.message,
        traceId: actualTraceId,
      });
      throw error;
    }
  }
  
  async syncAllReturns(): Promise<SyncResult[]> {
    this.logger.info('Starting return sync for all shops');
    
    const shops = await this.getRegisteredShops();
    const results: SyncResult[] = [];
    
    for (const shop of shops) {
      const traceId = this.generateTraceId();
      
      try {
        const returns = await this.syncReturns(
          shop.shopId,
          shop.platform,
          undefined,
          traceId
        );
        
        await this.uploadReturns(returns, shop.tenantId, traceId);
        
        results.push({
          shopId: shop.shopId,
          platform: shop.platform,
          returnsSynced: returns.length,
          errors: [],
          traceId,
        });
      } catch (error: any) {
        results.push({
          shopId: shop.shopId,
          platform: shop.platform,
          returnsSynced: 0,
          errors: [error.message],
          traceId,
        });
      }
    }
    
    this.logger.info('Return sync completed for all shops', {
      totalShops: shops.length,
      successCount: results.filter(r => r.errors.length === 0).length,
    });
    
    return results;
  }
  
  async getReturnStatus(
    platform: string,
    returnId: string,
    traceId?: string
  ): Promise<ReturnData> {
    const actualTraceId = traceId || this.generateTraceId();
    
    const adapter = this.platformAdapters.get(platform.toLowerCase());
    if (!adapter) {
      throw new Error(`Unsupported platform: ${platform}`);
    }
    
    return adapter.getReturnById(returnId, actualTraceId);
  }
  
  private async getRegisteredShops(): Promise<Array<{
    shopId: string;
    platform: string;
    tenantId: string;
  }>> {
    const data = await chrome.storage.local.get('shops');
    return data.shops || [];
  }
  
  private async uploadReturns(
    returns: ReturnData[],
    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/returns/batch`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Tenant-Id': tenantId,
        'X-Trace-Id': traceId,
      },
      body: JSON.stringify({
        returns,
        tenantId,
        traceId,
        businessType: 'TOC',
      }),
    });
    
    if (!response.ok) {
      throw new Error(`Upload failed: ${response.status}`);
    }
    
    this.logger.info('Returns uploaded', {
      count: returns.length,
      tenantId,
      traceId,
    });
  }
  
  private generateTraceId(): string {
    return `TRC-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  }
}
