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

/**
 * [BIZ_FIN_174] 供应商账期自动展期/缩短建议 (Terms)
 * @description 动态评估供应商信用、交期、退货率，建议调整账期以优化资金链。
 */
export class PaymentTermsService {
  private static readonly TERMS_TABLE = 'cf_payment_terms_recommendations';

  /**
   * 评估供应商账期调整建议
   */
  static async auditVendorPaymentTerms(tenantId: string, vendorId: string) {
    logger.info(`[PaymentTerms] Auditing payment terms for vendor: ${vendorId} for tenant: ${tenantId}`);

    // 1. 获取供应商的历史表现数据 (过去 180 天)
    const stats = await db('cf_purchase_orders')
      .where({ tenant_id: tenantId, supplier_id: vendorId })
      .andWhere('created_at', '>=', new Date(Date.now() - 180 * 24 * 60 * 60 * 1000))
      .select(
        db.raw('COUNT(id) as totalPOs'),
        db.raw('AVG(DATEDIFF(delivered_at, created_at)) as avgLeadTime'),
        db.raw('SUM(total_amount) as totalVolume')
      );

    const supplierStats = stats[0];
    const totalPOs = Number(supplierStats.totalPOs || 0);
    const avgLeadTime = Number(supplierStats.avgLeadTime || 0);
    const totalVolume = Number(supplierStats.totalVolume || 0);

    // 2. 评估建议策略
    let currentTerms = 30; // 默认 30 天账期
    let recommendedTerms = 30;
    let suggestion = 'MAINTAIN';
    let reason = 'Normal vendor performance';

    if (totalPOs > 20 && avgLeadTime < 7 && totalVolume > 50000) {
      // 优质供应商，且交期快，可以尝试展期 (延长付款时间，增加自身现金流)
      recommendedTerms = 45;
      suggestion = 'EXTEND';
      reason = 'High volume & fast lead time. High negotiation power.';
    } else if (avgLeadTime > 14 || totalPOs < 5) {
      // 表现不稳定或小额供应商，建议缩短账期 (减少对方欠款风险，或对方可能要求缩短)
      recommendedTerms = 15;
      suggestion = 'SHORTEN';
      reason = 'Slow lead time or low transaction frequency.';
    }

    const recommendation = {
      id: `TR-${tenantId}-${vendorId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      vendorId,
      currentTerms,
      recommendedTerms,
      suggestion,
      reason,
      created_at: new Date()
    };

    // 3. 存储建议记录
    await db(this.TERMS_TABLE)
      .insert(recommendation)
      .onConflict(['id'])
      .merge();

    return recommendation;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.TERMS_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.TERMS_TABLE} table...`);
      await db.schema.createTable(this.TERMS_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('vendorId', 128).notNullable();
        table.integer('currentTerms');
        table.integer('recommendedTerms');
        table.string('suggestion', 20); // E.g., EXTEND, SHORTEN, MAINTAIN
        table.text('reason');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'vendorId']);
      });
    }
  }
}
