import db from '../config/database';
import { logger } from '../utils/logger';

export interface SKUMapping {
  id?: number;
  tenantId: string;
  internalSkuId: string;
  platform: string;
  platformSkuId: string;
  platformProductId: string;
  isMain: boolean;
  metadata: any;
}

/**
 * [ERP_MST_01] 跨平台 SKU 身份映射引擎 (SKU Mapper)
 * @description 核心逻辑：建立内部商品 SKU 与各外部平台（1688, Amazon, Temu）SKU 的多对多映射关系。
 * 支持库存同步、订单归集时的 SKU 自动转换。
 * 遵循 Autocomplete-First (V31.5) 规范。
 */
export class SKUMappingService {
  private static readonly MAPPING_TABLE = 'cf_sku_mappings';

  /**
   * 初始化表结构
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.MAPPING_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.MAPPING_TABLE} table...`);
      await db.schema.createTable(this.MAPPING_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).index();
        table.string('internal_sku_id', 64).index();
        table.string('platform', 32).index();
        table.string('platform_sku_id', 64).index();
        table.string('platform_product_id', 64);
        table.boolean('is_main').defaultTo(false);
        table.json('metadata');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.timestamp('updated_at').defaultTo(db.fn.now());

        table.unique(['tenant_id', 'platform', 'platform_sku_id'], 'uk_platform_sku');
      });
      logger.info(`✅ Table ${this.MAPPING_TABLE} created`);
    }
  }

  /**
   * 绑定 SKU 映射 (SKU Binding)
   */
  static async bindSKU(mapping: SKUMapping) {
    logger.info(`[SKUMapper] Binding SKU: ${mapping.internalSkuId} -> ${mapping.platform}:${mapping.platformSkuId}`);
    
    await db(this.MAPPING_TABLE).insert({
      tenant_id: mapping.tenantId,
      internal_sku_id: mapping.internalSkuId,
      platform: mapping.platform,
      platform_sku_id: mapping.platformSkuId,
      platform_product_id: mapping.platformProductId,
      is_main: mapping.isMain,
      metadata: JSON.stringify(mapping.metadata)
    }).onConflict(['tenant_id', 'platform', 'platform_sku_id']).merge();
  }

  /**
   * 根据平台 SKU 反查内部 SKU (Reverse Lookup)
   */
  static async findInternalSKU(tenantId: string, platform: string, platformSkuId: string): Promise<string | null> {
    const mapping = await db(this.MAPPING_TABLE)
      .where({ tenant_id: tenantId, platform, platform_sku_id: platformSkuId })
      .first();
    return mapping ? mapping.internal_sku_id : null;
  }

  /**
   * 获取内部 SKU 的所有平台映射 (Forward Lookup)
   */
  static async getPlatformMappings(tenantId: string, internalSkuId: string): Promise<SKUMapping[]> {
    const mappings = await db(this.MAPPING_TABLE)
      .where({ tenant_id: tenantId, internal_sku_id: internalSkuId });
    
    return mappings.map(m => ({
      ...m,
      metadata: JSON.parse(m.metadata || '{}')
    }));
  }
}
