import { Request, Response } from 'express';
import { CustomerService } from '../../domains/Customer/CustomerService';
import { SupportService } from '../../domains/Customer/SupportService';
import { logger } from '../../utils/logger';

/**
 * [BIZ_CRM_10] & [BIZ_CSM_20] 客户成功与智能客服控制器
 */
export class CustomerController {
  /**
   * 获取租户所有售后争议
   * GET /api/v1/customer/disputes
   */
  static async getDisputes(req: Request, res: Response) {
    const tenantId = (req as any).traceContext?.tenantId || req.headers['x-tenant-id'] as string;
    const status = req.query.status as string;

    if (!tenantId) {
      return res.status(400).json({ success: false, error: 'Tenant context required' });
    }

    try {
      const disputes = await CustomerService.getDisputes(tenantId, status);
      return res.json({
        success: true,
        data: disputes
      });
    } catch (err: any) {
      logger.error(`[CustomerController] Get disputes failed: ${err.message}`);
      return res.status(500).json({ success: false, error: 'Internal server error' });
    }
  }

  /**
   * 同步售后事件 (通常由平台 Webhook 触发)
   * POST /api/v1/customer/disputes/sync
   */
  static async syncDispute(req: Request, res: Response) {
    const tenantId = (req as any).traceContext?.tenantId || req.headers['x-tenant-id'] as string;
    const disputeData = req.body;

    if (!tenantId) {
      return res.status(400).json({ success: false, error: 'Tenant context required' });
    }

    try {
      const disputeId = await CustomerService.syncDispute({
        ...disputeData,
        tenant_id: tenantId
      });

      return res.json({
        success: true,
        data: { disputeId }
      });
    } catch (err: any) {
      logger.error(`[CustomerController] Sync dispute failed: ${err.message}`);
      return res.status(500).json({ success: false, error: 'Internal server error' });
    }
  }

  /**
   * [BIZ_CSM_20] AGI 自动回复工单
   * POST /api/v1/customer/support/tickets/:ticketId/auto-reply
   */
  static async autoReply(req: Request, res: Response) {
    try {
      const { ticketId } = req.params;
      const { tenantId } = (req as any).traceContext;

      await SupportService.processNewTicket(tenantId, ticketId as string);
      res.json({ success: true, message: 'Auto-reply processed' });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }

  /**
   * [BIZ_CUS_15] AGI 自动审核售后 (RAG CS)
   * POST /api/v1/customer/after-sales/auto-audit
   */
  static async autoAudit(req: Request, res: Response) {
    try {
      const { disputeId, images } = req.body;
      const { tenantId } = (req as any).traceContext;

      logger.info(`[CustomerController] Initiating AGI auto-audit for dispute ${disputeId}`);

      // 1. 调用 AGI 逻辑识别图片损毁 (Mock)
      const damageDetected = images && images.length > 0;
      
      // 2. 自动退款审核
      if (damageDetected) {
        await CustomerService.updateDisputeStatus(disputeId, 'APPROVED', 'AGI auto-approved based on damage photo detection');
        res.json({ success: true, action: 'APPROVED', reason: 'Damage detected via AGI Vision' });
      } else {
        res.json({ success: true, action: 'PENDING_HUMAN', reason: 'No clear damage detected, escalating to manual review' });
      }
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }

  /**
   * 获取工单统计
   * GET /api/v1/customer/support/stats
   */
  static async getSupportStats(req: Request, res: Response) {
    try {
      const { tenantId } = (req as any).traceContext;
      const stats = await SupportService.getTicketStats(tenantId);
      res.json({ success: true, data: stats });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }
}
