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

export interface SourcingPool {
  id: string;
  commodity: string;
  targetQuantity: number;
  currentQuantity: number;
  status: 'OPEN' | 'NEGOTIATING' | 'ORDERED' | 'CLOSED';
  deadline: Date;
  participants: string[];
  estimatedSavingRate: number;
}

/**
 * [BIZ_FIN_18] 跨租户大宗商品集中采购议价池 (Pool Sourcing)
 * @description 核心逻辑：利用规模效应降低采购成本。系统自动发现跨租户的相似原材料需求，
 * 建立集中议价池，并代表池内所有租户向供应商发起议价。
 */
export class PoolSourcingService {
  private static readonly POOL_TABLE = 'cf_sourcing_pools';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.POOL_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.POOL_TABLE} table...`);
      await db.schema.createTable(this.POOL_TABLE, (table) => {
        table.string('id', 64).primary();
        table.string('commodity', 50).notNullable();
        table.decimal('target_quantity', 15, 2);
        table.decimal('current_quantity', 15, 2).defaultTo(0);
        table.string('status', 16).defaultTo('OPEN');
        table.datetime('deadline');
        table.json('participants'); // 存储租户 ID 数组
        table.float('estimated_saving_rate');
        table.timestamps(true, true);
        table.index(['commodity', 'status']);
      });
    }
  }

  /**
   * 自动发现并创建/加入议价池
   */
  static async processSourcingDemand(tenantId: string, commodity: string, quantity: number): Promise<string> {
    // Feature Flag Check
    if (!(await FeatureGovernanceService.isEnabled('BIZ_FIN_POOL_SOURCING', tenantId))) {
      logger.warn(`[PoolSourcing] Service disabled for tenant ${tenantId}`);
      return 'DISABLED';
    }

    logger.info(`[PoolSourcing] Processing demand for ${commodity}: ${quantity} units from ${tenantId}`);

    // 1. 查找现有的同类开放池
    const existingPool = await db(this.POOL_TABLE)
      .where({ commodity, status: 'OPEN' })
      .andWhere('deadline', '>', new Date())
      .first();

    if (existingPool) {
      // 2. 加入现有池
      const participants = JSON.parse(existingPool.participants);
      if (!participants.includes(tenantId)) {
        participants.push(tenantId);
      }

      await db(this.POOL_TABLE).where({ id: existingPool.id }).update({
        current_quantity: existingPool.current_quantity + quantity,
        participants: JSON.stringify(participants),
        updated_at: new Date()
      });

      logger.info(`[PoolSourcing] Tenant ${tenantId} joined pool ${existingPool.id}`);
      return existingPool.id;
    } else {
      // 3. 创建新池
      const poolId = `POOL-${commodity.toUpperCase()}-${Date.now()}`;
      await db(this.POOL_TABLE).insert({
        id: poolId,
        commodity,
        target_quantity: quantity * 5, // 假设目标是 5 倍
        current_quantity: quantity,
        status: 'OPEN',
        deadline: new Date(Date.now() + 7 * 24 * 3600 * 1000), // 7天后
        participants: JSON.stringify([tenantId]),
        estimated_saving_rate: 0.12, // 预计节省 12%
        created_at: new Date()
      });

      logger.info(`[PoolSourcing] Created new sourcing pool: ${poolId}`);
      return poolId;
    }
  }

  /**
   * 执行议价池最终结算与通知
   */
  static async finalizePool(poolId: string): Promise<void> {
    logger.info(`[PoolSourcing] Finalizing sourcing pool: ${poolId}`);

    const pool = await db(this.POOL_TABLE).where({ id: poolId }).first();
    if (!pool || pool.status !== 'OPEN') return;

    // 1. 模拟 AGI 议价逻辑
    // 逻辑：如果当前量达到目标的 80%，则议价成功，获得折扣
    const isSuccess = pool.current_quantity / pool.target_quantity >= 0.8;
    const finalSavingRate = isSuccess ? pool.estimated_saving_rate : 0.02; // 失败也有 2% 基础量级折扣

    // 2. 更新池状态
    await db(this.POOL_TABLE).where({ id: poolId }).update({
      status: isSuccess ? 'ORDERED' : 'CLOSED',
      estimated_saving_rate: finalSavingRate,
      updated_at: new Date()
    });

    // 3. 通知所有参与租户
    const participants = JSON.parse(pool.participants);
    for (const tenantId of participants) {
      logger.info(`[PoolSourcing] Notifying tenant ${tenantId} of pool ${poolId} result. Saving: ${finalSavingRate * 100}%`);
      
      // 联动消息中心或工单系统
      // await MessageService.sendNotification(tenantId, ...);
    }
  }
}
