import db from '../../config/database';
import { logger } from '../../utils/logger';
import { OrderProfitService } from '../Finance/OrderProfitService';
import { LogisticTelemetryService } from '../Logistics/LogisticTelemetryService';

export interface DisputeEvidence {
  orderId: string;
  customerDid: string;
  disputeReason: string;
  evidenceUrls: string[];
}

/**
 * [BIZ_CSM_30] 智能争议仲裁建议 (Dispute Arbitration)
 * @description 自动化处理售后纠纷，基于证据链给出赔付或驳回建议。
 */
export class DisputeArbitrationService {
  private static readonly DISPUTE_TABLE = 'cf_dispute_arbitrations';

  /**
   * 执行自动化仲裁分析
   */
  static async analyzeDispute(tenantId: string, evidence: DisputeEvidence) {
    logger.info(`[Arbitration] Analyzing dispute for order: ${evidence.orderId}`);

    // 1. 聚合全链路证据 (订单 P&L, 物流轨迹, 支付状态)
    const orderProfit = await db('cf_order_profits').where({ tenant_id: tenantId, order_id: evidence.orderId }).first();
    const logistics = await db('cf_logistic_telemetry').where({ tenant_id: tenantId, order_id: evidence.orderId }).first();
    const order = await db('cf_consumer_orders').where({ tenant_id: tenantId, order_id: evidence.orderId }).first();

    if (!order) return null;

    // 2. AGI 仲裁逻辑 (基于规则 + 因果叙述)
    let decision: 'APPROVE_REFUND' | 'REJECT_REFUND' | 'MANUAL_REVIEW' = 'MANUAL_REVIEW';
    let causalChain = '';

    const isDelivered = logistics?.status === 'DELIVERED';
    const profitAmount = orderProfit ? Number(orderProfit.net_profit) : 0;

    if (evidence.disputeReason.includes('NOT_RECEIVED') && isDelivered) {
      decision = 'REJECT_REFUND';
      causalChain = `物流轨迹显示订单已于 ${logistics.updated_at} 妥投，买家主张“未收到”与证据冲突。`;
    } else if (evidence.disputeReason.includes('QUALITY_ISSUE') && profitAmount > 100) {
      decision = 'MANUAL_REVIEW';
      causalChain = `高客单价订单 (利润 $${profitAmount})，需人工审核质量证据。`;
    } else if (evidence.disputeReason.includes('DELAYED_DELIVERY') && !isDelivered) {
      decision = 'APPROVE_REFUND';
      causalChain = `订单已严重超时且未妥投，符合自动退款条件。`;
    }

    // 3. 记录仲裁结果建议
    const arbitrationId = `ARB-${evidence.orderId}-${Date.now()}`;
    const arbitration = {
      id: arbitrationId,
      tenant_id: tenantId,
      order_id: evidence.orderId,
      customer_did: evidence.customerDid,
      dispute_reason: evidence.disputeReason,
      decision_suggested: decision,
      causal_chain: causalChain,
      status: 'SUGGESTED',
      created_at: new Date()
    };

    await db(this.DISPUTE_TABLE).insert(arbitration);

    logger.info(`[Arbitration] Suggested decision for ${evidence.orderId}: ${decision}`);

    return arbitration;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.DISPUTE_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.DISPUTE_TABLE} table...`);
      await db.schema.createTable(this.DISPUTE_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenant_id', 64).notNullable();
        table.string('order_id', 64).notNullable();
        table.string('customer_did', 128);
        table.string('dispute_reason', 256);
        table.string('decision_suggested', 32);
        table.text('causal_chain');
        table.string('status', 32);
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenant_id', 'order_id']);
        table.index(['status']);
      });
    }
  }
}
