import { logger } from '../../utils/logger';
import { SupplierInquiryService } from '../../services/SupplierInquiryService';
import db from '../../config/database';
import { AuditService } from '../../services/AuditService';
import { TradeService } from './TradeService';

export enum InquiryStatus {
  DRAFTED = 'DRAFTED',
  REVIEWED = 'REVIEWED',
  SENT = 'SENT',
  REPLIED = 'REPLIED',
  CONCLUDED = 'CONCLUDED',
  REJECTED = 'REJECTED'
}

export interface InquiryRecord {
  id: string;
  tenantId: string;
  productId: string;
  supplierId: string;
  status: InquiryStatus;
  aiMessage: string;
  humanMessage?: string;
  response?: string;
  targetQuantity: number;
  suggestedPrice?: number;
  traceId: string;
  createdAt: Date;
  updatedAt: Date;
}

/**
 * [BIZ_SC_11] 供应链人机协同询盘流 (Semi-Inquiry Flow)
 * @description 管理从 AI 生成到人工复核，再到供应商回复的全链路
 */
export class SourcingDomainService {
  private static readonly TABLE_NAME = 'cf_inquiries';

  /**
   * 1. 启动 AI 拟人化询盘生成
   */
  static async startInquiryProcess(params: {
    tenantId: string;
    productId: string;
    productTitle: string;
    attributes: Record<string, string>;
    targetQuantity: number;
    platform: string;
    supplierId: string;
    traceId: string;
  }): Promise<InquiryRecord> {
    logger.info(`[Sourcing] Starting AI inquiry for Product: ${params.productTitle}, Tenant: ${params.tenantId}`);

    // 调用 AI 服务生成询盘
    const aiResult = await SupplierInquiryService.generateInquiry({
      productTitle: params.productTitle,
      attributes: params.attributes,
      targetQuantity: params.targetQuantity,
      platform: params.platform
    });

    const inquiry: InquiryRecord = {
      id: `INQ-${Date.now()}`,
      tenantId: params.tenantId,
      productId: params.productId,
      supplierId: params.supplierId,
      status: InquiryStatus.DRAFTED,
      aiMessage: aiResult.message,
      targetQuantity: params.targetQuantity,
      suggestedPrice: aiResult.suggestedPrice,
      traceId: params.traceId,
      createdAt: new Date(),
      updatedAt: new Date()
    };

    // 持久化到数据库
    await db(this.TABLE_NAME).insert({
      id: inquiry.id,
      tenant_id: inquiry.tenantId,
      product_id: inquiry.productId,
      supplier_id: inquiry.supplierId,
      status: inquiry.status,
      ai_message: inquiry.aiMessage,
      target_quantity: inquiry.targetQuantity,
      suggested_price: inquiry.suggestedPrice,
      trace_id: inquiry.traceId,
      created_at: inquiry.createdAt,
      updated_at: inquiry.updatedAt
    });

    return inquiry;
  }

  /**
   * 2. 人工复核询盘逻辑 (Semi-AI)
   */
  static async reviewInquiry(inquiryId: string, finalMessage: string): Promise<void> {
    logger.info(`[Sourcing] Inquiry ${inquiryId} reviewed by human.`);
    
    await db(this.TABLE_NAME).where({ id: inquiryId }).update({ 
      human_message: finalMessage, 
      status: InquiryStatus.REVIEWED,
      updated_at: new Date()
    });
  }

  /**
   * 3. 发送询盘到供应商
   */
  static async sendToSupplier(inquiryId: string): Promise<boolean> {
    logger.info(`[Sourcing] Sending inquiry ${inquiryId} to supplier.`);
    
    const inquiry = await db(this.TABLE_NAME).where({ id: inquiryId }).first();
    if (!inquiry) throw new Error('Inquiry not found');

    const messageToSend = inquiry.human_message || inquiry.ai_message;
    
    // 调用 IM 网关发送消息 (Mock)
    const success = true; 
    
    if (success) {
      await db(this.TABLE_NAME).where({ id: inquiryId }).update({ 
        status: InquiryStatus.SENT,
        updated_at: new Date()
      });
    }

    return success;
  }

  /**
   * [BIZ_TRADE_04] 供应商风险评级与自动优选
   * @description 基于历史交付表现、价格稳定性与合规性进行 AI 动态评级
   */
  static async evaluateSupplierRisk(supplierId: string): Promise<{ 
    riskLevel: 'LOW' | 'MEDIUM' | 'HIGH';
    score: number;
    advice: string;
  }> {
    logger.info(`[Sourcing] Evaluating risk for Supplier: ${supplierId}`);

    // 1. 获取历史询盘与订单表现 (示例逻辑)
    const history = await db(this.TABLE_NAME).where({ supplier_id: supplierId }).limit(50);
    const successRate = history.filter(h => h.status === InquiryStatus.CONCLUDED).length / (history.length || 1);

    // 2. 模拟评级
    let riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' = 'LOW';
    let score = successRate * 100;

    if (score < 40) riskLevel = 'HIGH';
    else if (score < 70) riskLevel = 'MEDIUM';

    return {
      riskLevel,
      score,
      advice: riskLevel === 'HIGH' ? '该供应商历史达成率极低，建议寻找备选货源。' : '供应商表现稳定，可继续合作。'
    };
  }

  /**
   * [BIZ_AUTO_01] 自动采购机器人：接受询盘结果并转采购单
   * @description 当询盘成功后，自动下单并锁定库存，消除人工干预
   */
  static async acceptAndAutoPurchase(inquiryId: string, context: {
    tenantId: string;
    userId: string;
    traceId: string;
  }): Promise<{ poId: string; status: string }> {
    logger.info(`[Sourcing] Accepting inquiry: ${inquiryId} and initiating auto-purchase`);

    // 1. 获取询盘详情
    const inquiry = await db(this.TABLE_NAME).where({ id: inquiryId }).first();
    if (!inquiry) {
      throw new Error(`Inquiry ${inquiryId} not found`);
    }

    if (inquiry.status === InquiryStatus.CONCLUDED) {
      throw new Error(`Inquiry ${inquiryId} already concluded`);
    }

    // 2. 更新询盘状态
    await db(this.TABLE_NAME).where({ id: inquiryId }).update({
      status: InquiryStatus.CONCLUDED,
      updated_at: new Date()
    });

    // 3. 自动生成采购单 (BIZ_AUTO_01)
    const poId = await TradeService.createPurchaseOrder({
      tenantId: context.tenantId,
      productId: inquiry.product_id,
      supplierId: inquiry.supplier_id,
      quantity: inquiry.target_quantity,
      unitPrice: inquiry.suggested_price || 0,
      totalAmount: (inquiry.suggested_price || 0) * inquiry.target_quantity,
      traceId: context.traceId
    });

    // 4. 记录审计日志
    await AuditService.log({
      tenantId: context.tenantId,
      userId: context.userId,
      module: 'TRADE',
      action: 'AUTO_PURCHASE',
      resourceType: 'inquiry',
      resourceId: inquiryId,
      afterSnapshot: { inquiryId, poId, status: 'CONCLUDED' },
      result: 'success',
      traceId: context.traceId,
      source: 'node'
    });

    logger.info(`[Sourcing] Auto-purchase successful for Inquiry: ${inquiryId}, PO: ${poId}`);
    return { poId, status: 'CONCLUDED' };
  }
}
