import { ConsumerOrderService } from './domains/Trade/ConsumerOrderService';
import db from './config/database';
import { DomainBootstrap } from './core/runtime/DomainBootstrap';
import { DomainRegistry } from './core/runtime/DomainRegistry';

async function testOrchestrator() {
  console.log('🚀 Testing Order Orchestrator & Auto-Heal (BIZ_ORD_05)...');

  try {
    await DomainBootstrap.init();
    await DomainRegistry.bootstrap();
    await ConsumerOrderService.initTable();

    const tenantId = 'test-tenant';
    const shopId = 'test-shop';

    // 1. 创建测试订单 (包含 PO Box 异常)
    console.log('--- Test 1: Logistics Forbidden Zone ---');
    const orderId1 = await ConsumerOrderService.syncPlatformOrder({
      tenant_id: tenantId,
      shop_id: shopId,
      platform: 'AMAZON',
      site: 'US',
      platform_order_id: 'AMZ-1001',
      customer_name: 'John Doe',
      shipping_address: { city: 'NY', address: 'PO Box 1234' },
      items: [{ sku: 'SKU-001', quantity: 1, price: 50 }],
      total_amount: 50,
      status: 'PAID'
    });
    
    const order1 = await db('cf_consumer_orders').where({ id: orderId1 }).first();
    console.log(`Order 1 Status: ${order1.status}, Reason: ${order1.exception_reason}`);
    if (order1.status === 'EXCEPTION' && order1.exception_reason.includes('Forbidden zone')) {
      console.log('✅ Forbidden zone detection verified');
    }

    // 2. 创建高价值订单
    console.log('\n--- Test 2: High Value Audit ---');
    const orderId2 = await ConsumerOrderService.syncPlatformOrder({
      tenant_id: tenantId,
      shop_id: shopId,
      platform: 'SHOPIFY',
      site: 'US',
      platform_order_id: 'SHP-2002',
      customer_name: 'Rich Client',
      shipping_address: { city: 'LA', address: '123 Luxury St' },
      items: [{ sku: 'GOLD-SKU', quantity: 1, price: 6000 }],
      total_amount: 6000,
      status: 'PAID'
    });
    
    const order2 = await db('cf_consumer_orders').where({ id: orderId2 }).first();
    console.log(`Order 2 Status: ${order2.status}, Reason: ${order2.exception_reason}`);
    if (order2.status === 'EXCEPTION' && order2.exception_reason.includes('High value')) {
      console.log('✅ High value audit verified');
    }

    // 3. 模拟异常自愈 (手动触发)
    console.log('\n--- Test 3: Auto-Heal (Stock Out) ---');
    // 先手动设置一个订单为 EXCEPTION (Stock Out)
    const orderId3 = await ConsumerOrderService.syncPlatformOrder({
      tenant_id: tenantId,
      shop_id: shopId,
      platform: 'ALIEXPRESS',
      site: 'US',
      platform_order_id: 'ALI-3003',
      items: [{ sku: 'OUT-OF-STOCK', quantity: 1, price: 20, mainImage: 'https://example.com/item.jpg' }],
      total_amount: 20,
      status: 'PAID'
    });
    
    // 强制触发自愈逻辑 (假设 runHealthCheck 已经识别了异常，这里我们手动调用 attemptAutoHeal 来验证寻源)
    // 注意：在真实代码中，这是由 runHealthCheck 触发的
    await ConsumerOrderService.transitionStatus(tenantId, orderId3, 'EXCEPTION', 'Stock out');
    await (ConsumerOrderService as any).attemptAutoHeal(tenantId, orderId3, 'STOCK_OUT');

    const order3 = await db('cf_consumer_orders').where({ id: orderId3 }).first();
    console.log(`Order 3 Status: ${order3.status}, Auto-Heal: ${order3.auto_heal_status}, Reason: ${order3.exception_reason}`);
    if (order3.auto_heal_status === 'HEALED' && order3.status === 'PROCESSING') {
      console.log('✅ Auto-heal via rerouting verified');
    }

  } catch (error) {
    console.error('❌ Test failed:', error);
  } finally {
    await db.destroy();
  }
}

testOrchestrator();
