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

/**
 * [BIZ_FIN_167] 采购预付款比例信用分级调整建议 (Credit)
 * @description 优化资金链，建议调整采购预付款比例。
 */
export class VendorCreditService {
  private static readonly CREDIT_TABLE = 'cf_vendor_credit_adjustments';

  /**
   * 建议预付款比例调整
   */
  static async suggestPrepaymentAdjustment(tenantId: string, vendorId: string) {
    logger.info(`[VendorCredit] Suggesting adjustment for vendor: ${vendorId} for tenant: ${tenantId}`);

    // 1. 获取供应商历史表现 (交付成功率、超时率)
    const stats = await db('cf_purchase_orders')
      .where({ supplier_id: vendorId, tenant_id: tenantId })
      .select(
        db.raw('COUNT(id) as totalPOs'),
        db.raw('SUM(CASE WHEN status = "DELIVERED" THEN 1 ELSE 0 END) as deliveredPOs'),
        db.raw('AVG(DATEDIFF(delivered_at, created_at)) as avgLeadTime')
      );

    const totalPOs = Number(stats[0].totalPOs || 0);
    const deliveredPOs = Number(stats[0].deliveredPOs || 0);
    const deliveryRate = totalPOs > 0 ? deliveredPOs / totalPOs : 0;

    // 2. 评估建议预付款比例
    let currentRatio = 0.3; // 默认 30%
    let suggestedRatio = 0.3;
    let suggestion = 'MAINTAIN';
    let reason = 'Stable vendor performance';

    if (deliveryRate > 0.95 && totalPOs > 50) {
      // 优质供应商，建议降低预付款比例 (增加自身资金流动性)
      suggestedRatio = 0.1;
      suggestion = 'REDUCE_PREPAYMENT';
      reason = `High delivery rate (${(deliveryRate * 100).toFixed(0)}%) and high volume. High trust level.`;
    } else if (deliveryRate < 0.8 && totalPOs > 10) {
      // 风险供应商，建议提高预付款比例或加强风控
      suggestedRatio = 0.5;
      suggestion = 'INCREASE_PREPAYMENT_ESCROW';
      reason = `Low delivery rate (${(deliveryRate * 100).toFixed(0)}%). High risk.`;
    }

    const adjustment = {
      id: `VC-${tenantId}-${vendorId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      vendorId,
      currentRatio,
      suggestedRatio,
      suggestion,
      reason,
      created_at: new Date()
    };

    // 3. 存储建议
    await db(this.CREDIT_TABLE)
      .insert(adjustment)
      .onConflict(['id'])
      .merge();

    return adjustment;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.CREDIT_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.CREDIT_TABLE} table...`);
      await db.schema.createTable(this.CREDIT_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('vendorId', 128).notNullable();
        table.decimal('currentRatio', 5, 4);
        table.decimal('suggestedRatio', 5, 4);
        table.string('suggestion', 32);
        table.text('reason');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'vendorId']);
      });
    }
  }
}
