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

/**
 * [BIZ_OPS_148] 供应商开票延迟影响账期建议 (Invoicing)
 * @description 核心逻辑：基于历史开票时长，预测供应商是否会延迟提供发票，评估对租户进项抵扣与资金链的影响。
 */
export class InvoiceLateRiskService {
  /**
   * 评估开票风险 (BIZ_OPS_148)
   */
  static async evaluateInvoicingRisk(tenantId: string, supplierId: string): Promise<any> {
    logger.info(`[InvoiceRisk] Evaluating invoicing risk for Supplier: ${supplierId}, Tenant: ${tenantId}`);

    try {
      // 1. 获取供应商历史开票时效 (模拟)
      const avgInvoiceDays = 12.5; // 模拟平均 12.5 天开票
      const threshold = 10;

      // 2. 识别风险：如果超过 10 天
      if (avgInvoiceDays > threshold) {
        const impactValue = 5000; // 模拟影响金额 (如进项抵扣延迟)
        const advice = `INVOICE DELAY RISK: Supplier typically takes ${avgInvoiceDays} days to invoice (Threshold: ${threshold}d). ` +
          `Potential cashflow impact: ${impactValue} in delayed tax credits. Suggesting negotiation for shorter terms.`;

        // 3. [UX_XAI_01] 记录决策证据链
        await DecisionExplainabilityEngine.logDecision({
          tenantId,
          module: 'FINANCIAL_COMPLIANCE',
          resourceId: supplierId,
          decisionType: 'INVOICING_DELAY_RISK',
          causalChain: advice,
          factors: [
            { name: 'AvgInvoiceDays', value: avgInvoiceDays, weight: 0.8, impact: 'NEGATIVE' },
            { name: 'FinancialImpact', value: impactValue, weight: 0.2, impact: 'NEGATIVE' }
          ],
          traceId: 'invoice-risk-' + Date.now()
        });

        return { success: true, riskLevel: 'MEDIUM', avgInvoiceDays, advice, status: 'PENDING_REVIEW' };
      }

      return { success: true, riskLevel: 'LOW', message: 'Invoicing performance is within limits' };
    } catch (err: any) {
      logger.error(`[InvoiceRisk][WARN] Evaluation failed: ${err.message}`);
      return { success: false, error: err.message };
    }
  }
}
