import { logger } from '../../utils/logger';
import { PluginManager } from '../runtime/PluginManager';

export interface PlatformProduct {
  externalId: string;
  title: string;
  description: string;
  price: number;
  currency: string;
  images: string[];
  skus: any[];
  platform?: string;
  category?: string;
  attributes?: Record<string, any>;
  // [CORE_INT_04] 独立站特有属性 (Independent Station Specifics)
  seo?: {
    title?: string;
    description?: string;
    tags?: string[];
  };
  metafields?: Record<string, any>;
  productType?: string;
  vendor?: string;
}

export interface PublishResult {
  success: boolean;
  externalId?: string;
  publishUrl?: string;
  error?: string;
}

/**
 * [CORE_INT_01] 平台连接器标准协议 (Platform Connector Protocol)
 * @description 统一所有电商平台的授权、采集、发布与同步逻辑
 */
export interface IPlatformConnector {
  platformCode: string;
  capabilities: {
    hasApi: boolean;
    supportsPriceSync: boolean;
    supportsInventorySync: boolean;
    supportsOrderPull: boolean;
  };

  /**
   * 平台授权校验
   */
  authorize(shopId: string): Promise<boolean>;

  /**
   * 拉取店铺商品
   */
  pullProducts(shopId: string, params?: any): Promise<PlatformProduct[]>;

  /**
   * 推送商品上架
   */
  pushListing(shopId: string, product: PlatformProduct): Promise<PublishResult>;

  /**
   * 更新商品价格
   */
  updatePrice(shopId: string, externalId: string, newPrice: number): Promise<boolean>;

  /**
   * 同步库存
   */
  syncInventory(shopId: string, externalId: string, quantity: number): Promise<boolean>;

  /**
   * [BIZ_TOC_03] 计算实时运费
   */
  calculateShipping?(shopId: string, params: {
    countryCode: string;
    zipCode?: string;
    weight: number;
    dimensions?: any;
  }): Promise<{ carrier: string; cost: number; currency: string; estimatedDays: number }>;
}

/**
 * [CORE_INT_01] 平台连接器总线 (Connector Bus)
 */
export class ConnectorBus {
  private static connectors: Map<string, IPlatformConnector> = new Map();

  /**
   * 注册平台连接器
   */
  static register(connector: IPlatformConnector) {
    logger.info(`[ConnectorBus] Registering connector for: ${connector.platformCode}`);
    this.connectors.set(connector.platformCode, connector);
  }

  /**
   * 获取指定平台的连接器
   */
  static getConnector(platformCode: string): IPlatformConnector {
    const connector = this.connectors.get(platformCode);
    if (!connector) {
      throw new Error(`Connector for platform ${platformCode} not found`);
    }
    return connector;
  }

  /**
   * 推送商品上架 (Plugin-Driven Flow)
   */
  static async pushListing(platformCode: string, shopId: string, product: PlatformProduct): Promise<PublishResult> {
    const connector = this.getConnector(platformCode);
    
    // 1. 触发发布前钩子 (Pre-Publish Hooks: 如 SEO 自动填充、敏感词过滤)
    const processedProduct = await PluginManager.triggerHook('onBeforePublish', { product, platformCode, shopId });
    
    // 2. 执行核心发布逻辑
    const result = await connector.pushListing(shopId, processedProduct.product);
    
    // 3. 触发发布后钩子 (Post-Publish Hooks: 如 自动推送到营销日历、通知 Webhook)
    await PluginManager.triggerHook('onAfterPublish', { result, product: processedProduct.product, platformCode, shopId });
    
    return result;
  }

  /**
   * 获取所有支持 API 的平台
   */
  static getApiPlatforms(): string[] {
    return Array.from(this.connectors.values())
      .filter(c => c.capabilities.hasApi)
      .map(c => c.platformCode);
  }
}
