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

export interface ReconciliationResult {
  orderId: string;
  expectedAmount: number;
  actualAmount: number;
  discrepancy: number;
  reason: string;
  status: 'MATCHED' | 'DISCREPANCY' | 'PENDING';
}

/**
 * [ERP_FIN_01] 财务对账与收支差异分析引擎 (Reconciliation)
 * @description 核心逻辑：支持「应收/实收/费用/税费」的自动对账与差异下钻，识别平台结算与实际订单的差异。
 */
export class FinanceReconService {
  private static readonly TABLE_NAME = 'cf_finance_reconciliation';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const exists = await db.schema.hasTable(this.TABLE_NAME);
    if (!exists) {
      logger.info(`📦 Creating ${this.TABLE_NAME} table...`);
      await db.schema.createTable(this.TABLE_NAME, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.string('order_id', 64).notNullable();
        table.decimal('expected_amount', 10, 2);
        table.decimal('actual_amount', 10, 2);
        table.decimal('discrepancy', 10, 2);
        table.string('reason', 512);
        table.string('status', 32).defaultTo('PENDING');
        table.string('trace_id', 64);
        table.timestamps(true, true);

        table.index(['tenant_id', 'status']);
        table.index('order_id');
      });
      logger.info(`✅ Table ${this.TABLE_NAME} created`);
    }
  }

  /**
   * [ERP_FIN_01] 执行自动对账 (Auto Reconciliation)
   */
  static async performReconciliation(tenantId: string, orderIds: string[]): Promise<ReconciliationResult[]> {
    logger.info(`[FinanceRecon] Starting reconciliation for Tenant: ${tenantId}, Count: ${orderIds.length}`);
    const traceId = `recon-${Date.now()}`;
    const results: ReconciliationResult[] = [];

    for (const orderId of orderIds) {
      // 1. 获取订单应收 (Expected Amount)
      const order = await db('cf_order').where({ id: orderId, tenant_id: tenantId }).first();
      if (!order) {
        logger.warn(`[FinanceRecon] Order ${orderId} not found, skipping.`);
        continue;
      }

      // 2. 获取实际结算 (Actual Amount) - 假设从 cf_settlement_records 汇总
      const settlement = await db('cf_settlement_records')
        .where({ order_id: orderId, tenant_id: tenantId })
        .sum('amount as total')
        .first();

      const expected = Number(order.total_amount || 0);
      const actual = Number(settlement?.total || 0);
      const discrepancy = actual - expected;

      let status: ReconciliationResult['status'] = 'MATCHED';
      let reason = 'Amount matched exactly';

      if (Math.abs(discrepancy) > 0.01) {
        status = 'DISCREPANCY';
        reason = `Amount mismatch: Expected $${expected.toFixed(2)}, Actual $${actual.toFixed(2)}. Discrepancy: $${discrepancy.toFixed(2)}.`;
      }

      // 3. 记录对账结果
      await db(this.TABLE_NAME).insert({
        tenant_id: tenantId,
        order_id: orderId,
        expected_amount: expected,
        actual_amount: actual,
        discrepancy: discrepancy,
        reason: reason,
        status: status,
        trace_id: traceId,
        created_at: new Date(),
        updated_at: new Date()
      });

      // 4. [UX_XAI_01] 记录差异分析证据链
      if (status === 'DISCREPANCY') {
        await DecisionExplainabilityEngine.logDecision({
          tenantId,
          module: 'FINANCE',
          resourceId: orderId,
          decisionType: 'FINANCIAL_RECONCILIATION_DISCREPANCY',
          causalChain: reason,
          factors: [
            { name: 'Expected', value: expected, weight: 0.5, impact: 'NEUTRAL' },
            { name: 'Actual', value: actual, weight: 0.5, impact: 'NEUTRAL' },
            { name: 'Gap', value: discrepancy, weight: 1.0, impact: 'NEGATIVE' }
          ],
          traceId
        });
      }

      results.push({ orderId, expectedAmount: expected, actualAmount: actual, discrepancy, reason, status });
    }

    return results;
  }
}
