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

/**
 * [BIZ_FIN_183] 售后退款路径原路返回一致性审计 (Refund)
 * @description 审计售后退款路径，防止内部洗钱或误退款。
 */
export class RefundAuditService {
  private static readonly AUDIT_TABLE = 'cf_refund_audit_logs';

  /**
   * 审计退款一致性
   */
  static async auditRefundConsistency(tenantId: string, refundId: string) {
    logger.info(`[RefundAudit] Auditing refund consistency for refund: ${refundId} for tenant: ${tenantId}`);

    // 1. 获取退款事务和原始支付事务
    const refundTx = await db('cf_transactions')
      .where({ id: refundId, tenant_id: tenantId, transaction_type: 'REFUND' })
      .first();

    if (!refundTx) return null;

    const originalTx = await db('cf_transactions')
      .where({ order_id: refundTx.order_id, tenant_id: tenantId, transaction_type: 'PAYMENT' })
      .first();

    if (!originalTx) return null;

    // 2. 检查路径一致性 (支付方式、收款账户等)
    let isConsistent = true;
    let anomalyReason = '';

    if (refundTx.payment_method !== originalTx.payment_method) {
      isConsistent = false;
      anomalyReason = `Refund method (${refundTx.payment_method}) differs from payment method (${originalTx.payment_method})`;
    } else if (refundTx.amount > originalTx.amount) {
      isConsistent = false;
      anomalyReason = `Refund amount (${refundTx.amount}) exceeds original payment (${originalTx.amount})`;
    }

    const auditLog = {
      id: `RA-${tenantId}-${refundId}`,
      tenantId,
      refundId,
      orderId: refundTx.order_id,
      isConsistent,
      anomalyReason,
      created_at: new Date()
    };

    // 3. 存储审计记录
    await db(this.AUDIT_TABLE)
      .insert(auditLog)
      .onConflict(['id'])
      .merge();

    return auditLog;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.AUDIT_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.AUDIT_TABLE} table...`);
      await db.schema.createTable(this.AUDIT_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('refundId', 64).notNullable();
        table.string('orderId', 64).notNullable();
        table.boolean('isConsistent').notNullable();
        table.text('anomalyReason');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'orderId']);
      });
    }
  }
}
