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

export enum DisputeStatus {
  PENDING_AI = 'PENDING_AI',
  AI_ANALYZING = 'AI_ANALYZING',
  AUTO_APPROVED = 'AUTO_APPROVED',
  MANUAL_INTERVENE = 'MANUAL_INTERVENE',
  RESOLVED = 'RESOLVED',
  CLOSED = 'CLOSED'
}

export interface Dispute {
  id: string;
  tenant_id: string;
  order_id: string;
  external_dispute_id: string;
  type: 'REFUND' | 'RETURN' | 'CHARGEBACK' | 'INQUIRY';
  reason: string;
  status: DisputeStatus;
  customer_message: string;
  evidence_images?: string[]; // [BIZ_CUS_15] 多模态证据图片
  platform_policy?: string;   // [BIZ_CUS_15] 匹配到的平台策略
  ai_analysis?: string;
  roi_impact?: number;
  created_at: Date;
  updated_at: Date;
}

/**
 * [BIZ_CRM_10] & [BIZ_CUS_15] 智能售后与客户成功服务 (Grounding Implementation)
 * @description 核心逻辑：实现售后 FSM 状态机、多模态 AGI 自动退款核算逻辑
 */
export class CustomerService {
  private static readonly TABLE_NAME = 'cf_disputes';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.TABLE_NAME);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.TABLE_NAME} table...`);
      await db.schema.createTable(this.TABLE_NAME, (table) => {
        table.string('id', 64).primary();
        table.string('tenant_id', 64).notNullable();
        table.string('order_id', 64).notNullable();
        table.string('external_dispute_id', 128).unique();
        table.string('type', 32).notNullable();
        table.string('reason', 255);
        table.string('status', 32).defaultTo(DisputeStatus.PENDING_AI);
        table.text('customer_message');
        table.json('evidence_images'); // [BIZ_CUS_15]
        table.text('platform_policy'); // [BIZ_CUS_15]
        table.text('ai_analysis');
        table.decimal('roi_impact', 10, 4);
        table.timestamps(true, true);

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

  /**
   * 创建/同步争议事件
   */
  static async syncDispute(data: Partial<Dispute>): Promise<string> {
    const id = data.id || `DSP-${Date.now()}`;
    
    const existing = await db(this.TABLE_NAME)
      .where({ external_dispute_id: data.external_dispute_id, tenant_id: data.tenant_id })
      .first();

    if (existing) {
      await db(this.TABLE_NAME).where({ id: existing.id }).update({
        status: data.status || existing.status,
        updated_at: db.fn.now()
      });
      return existing.id;
    }

    await db(this.TABLE_NAME).insert({
      ...data,
      id,
      status: DisputeStatus.PENDING_AI,
      created_at: db.fn.now(),
      updated_at: db.fn.now()
    });

    // 触发 AGI 自动分析
    this.analyzeDisputeWithAGI(id).catch(err => {
      logger.error(`[CustomerService] AGI Analysis failed for ${id}: ${err.message}`);
    });

    return id;
  }

  /**
   * [BIZ_CUS_15] AGI 多模态分析与判责核心逻辑
   */
  private static async analyzeDisputeWithAGI(disputeId: string) {
    const dispute = await db(this.TABLE_NAME).where({ id: disputeId }).first();
    if (!dispute) return;

    await db(this.TABLE_NAME).where({ id: disputeId }).update({ status: DisputeStatus.AI_ANALYZING });

    // 1. 获取关联订单与利润快照
    const order = await db('cf_consumer_orders').where({ id: dispute.order_id }).first();
    if (!order) {
      await db(this.TABLE_NAME).where({ id: disputeId }).update({ 
        status: DisputeStatus.MANUAL_INTERVENE,
        ai_analysis: 'Order not found, requires manual check.'
      });
      return;
    }

    const profitSnapshot = typeof order.profit_snapshot === 'string' 
      ? JSON.parse(order.profit_snapshot) 
      : order.profit_snapshot;

    // 2. RAG 驱动策略检索 (BIZ_CUS_15)
    const policy = await this.getPlatformPolicy(order.platform, dispute.reason);

    // 3. 多模态 AGI 语义与视觉分析 (BIZ_CUS_15)
    const evidenceImages = typeof dispute.evidence_images === 'string' 
      ? JSON.parse(dispute.evidence_images) 
      : (dispute.evidence_images || []);
    
    const aiResult = await AIService.analyzeMultiModalDispute({
      reason: dispute.reason,
      customerMessage: dispute.customer_message,
      imageUrls: evidenceImages,
      platform: order.platform
    }, dispute.tenant_id);

    // 4. ROI 影响核算 (Grounding: 务实落地逻辑)
    // 逻辑：如果退款后的净利 ROI 仍 > 5%，且金额 < $20，或者 AGI 强力推荐且符合政策，则自动放行
    const refundAmount = order.total_amount;
    const currentNetProfit = profitSnapshot?.net_profit || 0;
    const newNetProfit = currentNetProfit - refundAmount;
    const costBasis = (profitSnapshot?.purchasePrice + profitSnapshot?.logisticsCost) || 1;
    const roiImpact = newNetProfit / costBasis;

    let finalStatus = DisputeStatus.MANUAL_INTERVENE;
    let finalAnalysis = `${aiResult.aiSummary}\nPolicy: ${policy}`;

    const isWithinAutoRefundLimit = refundAmount < 20;
    const isROIAcceptable = roiImpact > 0.05;
    const isPolicyMatched = policy.includes('Auto-refund allowed');

    if (aiResult.recommendation === 'APPROVE' && isWithinAutoRefundLimit && (isROIAcceptable || isPolicyMatched)) {
      finalStatus = DisputeStatus.AUTO_APPROVED;
      finalAnalysis += `\n[Decision] AUTO_APPROVED (ROI after refund: ${(roiImpact * 100).toFixed(2)}%)`;
    } else if (aiResult.recommendation === 'REJECT' && !isPolicyMatched) {
      finalAnalysis += `\n[Decision] Recommendation: REJECT. Suggesting manual review before final rejection.`;
    }

    await db(this.TABLE_NAME).where({ id: disputeId }).update({
      status: finalStatus,
      ai_analysis: finalAnalysis,
      roi_impact: roiImpact,
      platform_policy: policy,
      updated_at: db.fn.now()
    });

    if (finalStatus === DisputeStatus.AUTO_APPROVED) {
      logger.info(`[CustomerService] Dispute ${disputeId} AUTO_APPROVED by Multimodal AGI`);
    }
  }

  /**
   * [BIZ_CUS_15] RAG 策略检索模拟
   */
  private static async getPlatformPolicy(platform: string, reason: string): Promise<string> {
    // 实际业务中应从向量数据库或配置中心检索
    const policies: Record<string, string> = {
      'Amazon_damage': 'Amazon: Damaged products under $20 with photo evidence can be auto-refunded.',
      'Amazon_wrong': 'Amazon: Wrong items require return unless value < $10.',
      'Temu_damage': 'Temu: Quality issues are strictly handled; auto-refund for trusted customers if < $15.',
      'Default': 'General: Manual review recommended for all disputes > $20.'
    };

    const key = `${platform}_${reason.includes('damage') ? 'damage' : reason.includes('wrong') ? 'wrong' : 'other'}`;
    return policies[key] || policies['Default'];
  }

  /**
   * 获取租户售后列表
   */
  static async getDisputes(tenantId: string, status?: string) {
    let query = db(this.TABLE_NAME).where({ tenant_id: tenantId });
    if (status) query = query.andWhere({ status });
    return query.orderBy('created_at', 'desc');
  }

  /**
   * [BIZ_CSM_20] 创建支持工单 (Support Ticket Entry)
   * @description 由系统自动触发或用户手动创建，记录到 cf_support_tickets 表
   */
  static async createSupportTicket(params: {
    tenantId: string;
    orderId: string;
    type: string;
    message: string;
    priority: 'NORMAL' | 'URGENT';
  }) {
    logger.info(`[CustomerService] Creating support ticket for Order ${params.orderId} | Tenant: ${params.tenantId}`);

    const ticketId = `TKT-${Date.now()}`;
    
    // 插入 cf_support_tickets 表 (与 SupportService 共享表)
    await db('cf_support_tickets').insert({
      id: ticketId,
      tenant_id: params.tenantId,
      customer_id: 'SYSTEM', // 自动触发
      subject: `[${params.type}] Logistics Update for Order ${params.orderId}`,
      message: params.message,
      status: 'OPEN',
      created_at: new Date(),
      updated_at: new Date()
    });

    // 这里可以联动 SupportService.processNewTicket(params.tenantId, ticketId) 进行 AGI 自动回复
    return ticketId;
  }

  /**
   * 更新争议状态
   */
  static async updateDisputeStatus(disputeId: string, status: string, reason: string) {
    await db(this.TABLE_NAME).where({ id: disputeId }).update({
      status,
      ai_analysis: reason,
      updated_at: db.fn.now()
    });
  }
}
