import db from '../config/database';
import { AuditService } from './AuditService';

/**
 * [BIZ_FIN_18] 跨租户大宗商品集中采购议价池
 * 负责聚合不同租户对同一大宗原材料（如包装纸箱、PE 塑料等）的需求，形成规模优势进行议价
 */
export class PoolSourcingService {
  /**
   * 租户加入采购池
   */
  static async joinPool(
    tenantId: string, 
    commodityType: string, 
    quantity: number, 
    traceId: string
  ): Promise<void> {
    await db.transaction(async (trx) => {
      // 1. 获取或创建该商品的采购池
      let pool = await trx('cf_pool_sourcing')
        .where({ commodity_type: commodityType, status: 'OPEN' })
        .forUpdate()
        .first();

      if (!pool) {
        const [id] = await trx('cf_pool_sourcing').insert({
          commodity_type: commodityType,
          total_pooled_quantity: 0,
          status: 'OPEN'
        });
        pool = { id, total_pooled_quantity: 0 };
      }

      // 2. 更新采购池总量
      const newQuantity = pool.total_pooled_quantity + quantity;
      await trx('cf_pool_sourcing')
        .where({ id: pool.id })
        .update({
          total_pooled_quantity: newQuantity,
          updated_at: db.fn.now()
        });

      // 3. 记录租户参与审计
      await AuditService.log({
        tenantId: tenantId,
        userId: 'SYSTEM',
        module: 'POOL_SOURCING',
        action: 'JOIN_POOLED_SOURCING',
        resourceType: 'POOLED_SOURCING',
        resourceId: pool.id.toString(),
        traceId: traceId,
        afterSnapshot: JSON.stringify({ quantity, newTotal: newQuantity }),
        result: 'success',
        source: 'node',
        metadata: { commodityType }
      });
    });
  }

  /**
   * 获取租户所有参与的采购池
   */
  static async getActivePools() {
    return await db('cf_pool_sourcing')
      .where({ status: 'OPEN' })
      .orWhere({ status: 'NEGOTIATING' })
      .orderBy('total_pooled_quantity', 'desc');
  }
}
