import db from '../config/database';
import { AuditService } from './AuditService';
import { InventoryService } from './InventoryService';

/**
 * [BIZ_AUTO_12] 自动化退货质检与二次上架逻辑
 * 负责退货包裹的质量检查结果登记、残值评估及符合条件的商品自动二次上架
 */
export class AutoReturnQAService {
  /**
   * 登记质检结果并尝试自动上架
   */
  static async processReturnQA(
    tenantId: string,
    orderId: string,
    productId: string,
    qaResult: 'PASS' | 'REJECT' | 'REPAIR',
    qaDetails: any,
    traceId: string
  ): Promise<boolean> {
    // 1. 获取商品原价
    const product = await db('cf_product').where({ productId }).first();
    const originalPrice = product?.price || 0;

    // 2. 残值评估 (根据质检结果)
    let salvageValue = originalPrice;
    if (qaResult === 'REJECT') salvageValue = 0;
    else if (qaResult === 'REPAIR') salvageValue = originalPrice * 0.7; // 打 7 折作为残值

    // 3. 持久化质检记录
    const [id] = await db('cf_return_qa').insert({
      tenant_id: tenantId,
      order_id: orderId,
      product_id: productId,
      qa_result: qaResult,
      qa_details: JSON.stringify(qaDetails),
      salvage_value: salvageValue,
      relisted: false
    });

    // 4. 如果质检通过 (PASS)，自动增加库存以实现二次上架
    if (qaResult === 'PASS') {
      await db.transaction(async (trx) => {
        // 增加可用库存
        await InventoryService.updateStock(productId, tenantId, 1, 'RETURN_RELIST', traceId);

        // 更新质检记录的上架状态
        await trx('cf_return_qa')
          .where({ id })
          .update({
            relisted: true,
            updated_at: db.fn.now()
          });

        // 审计记录
        await AuditService.log({
          tenant_id: tenantId,
          action: 'RETURN_AUTO_RELIST',
          target_type: 'PRODUCT',
          target_id: productId,
          trace_id: traceId,
          new_data: JSON.stringify({ orderId, qaResult }),
          metadata: JSON.stringify({ salvageValue })
        });
      });
      return true;
    }

    return false;
  }

  /**
   * 汇总退货残值
   */
  static async getSalvageSummary(tenantId: string) {
    const summary = await db('cf_return_qa')
      .where({ tenant_id: tenantId })
      .select('qa_result')
      .count('* as count')
      .sum('salvage_value as total_salvage')
      .groupBy('qa_result');
    return summary;
  }
}
