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

async function testConsumerOrderService() {
  console.log('🚀 Testing ConsumerOrderService...');

  try {
    // 初始化环境
    await DomainBootstrap.init();
    await DomainRegistry.bootstrap();
    await ConsumerOrderService.initTable();

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

    // 1. 测试订单创建和同步
    console.log('\n--- Test 1: Order Creation and Sync ---');
    const orderId = await ConsumerOrderService.syncPlatformOrder({
      tenant_id: tenantId,
      shop_id: shopId,
      platform: 'SHOPIFY',
      site: 'US',
      platform_order_id: 'TEST-1001',
      customer_name: 'Test Customer',
      customer_email: 'test@example.com',
      shipping_address: { city: 'New York', address: '123 Test St' },
      items: [{ sku: 'SKU-001', quantity: 2, price: 50 }],
      total_amount: 100,
      currency: 'USD',
      status: 'UNPAID',
      payment_status: 'PENDING',
      fulfillment_status: 'PENDING',
      trace_id: `test-${Date.now()}`
    });
    console.log(`✅ Created order: ${orderId}`);

    // 2. 测试订单状态转换
    console.log('\n--- Test 2: Order Status Transition ---');
    await ConsumerOrderService.transitionStatus(tenantId, orderId, 'PAID');
    const orderAfterPaid = await db('cf_consumer_orders').where({ id: orderId }).first();
    console.log(`✅ Order status transitioned to: ${orderAfterPaid.status}`);

    // 3. 测试订单支付处理
    console.log('\n--- Test 3: Order Payment Processing ---');
    await ConsumerOrderService.processPayment(tenantId, orderId, {
      method: 'credit_card',
      transactionId: `TRX-${Date.now()}`
    });
    const orderAfterPayment = await db('cf_consumer_orders').where({ id: orderId }).first();
    console.log(`✅ Payment processed, payment status: ${orderAfterPayment.payment_status}`);

    // 4. 测试退款流程
    console.log('\n--- Test 4: Refund Process ---');
    const refundId = await ConsumerOrderService.requestRefund(tenantId, orderId, 'Test refund reason', 50);
    console.log(`✅ Refund requested: ${refundId}`);
    
    await ConsumerOrderService.approveRefund(tenantId, refundId, true, 'Approved for testing');
    const refund = await db('cf_refunds').where({ id: refundId }).first();
    console.log(`✅ Refund approved, status: ${refund.status}`);

    // 5. 测试售后流程
    console.log('\n--- Test 5: After-sales Process ---');
    // 先将订单状态更新为 DELIVERED
    await ConsumerOrderService.transitionStatus(tenantId, orderId, 'DELIVERED');
    
    const serviceId = await ConsumerOrderService.requestAfterSales(tenantId, orderId, 'EXCHANGE', 'Test exchange reason', [
      { sku: 'SKU-002', quantity: 1, price: 60 }
    ]);
    console.log(`✅ After-sales service requested: ${serviceId}`);
    
    await ConsumerOrderService.processAfterSales(tenantId, serviceId, 'APPROVE', 'Approved for testing');
    const service = await db('cf_after_sales').where({ id: serviceId }).first();
    console.log(`✅ After-sales service processed, status: ${service.status}`);

    // 6. 测试订单查询
    console.log('\n--- Test 6: Order Query ---');
    const orders = await ConsumerOrderService.getOrders(tenantId, { platform: 'SHOPIFY' });
    console.log(`✅ Found ${orders.total} orders`);

    // 7. 测试订单详情
    console.log('\n--- Test 7: Order Details ---');
    const orderDetails = await ConsumerOrderService.getOrderById(tenantId, orderId);
    console.log(`✅ Order details retrieved, customer: ${orderDetails.customer_name}`);

    // 8. 测试订单统计
    console.log('\n--- Test 8: Order Statistics ---');
    const stats = await ConsumerOrderService.getDetailedStats(tenantId);
    console.log(`✅ Statistics retrieved, total orders: ${stats.total_orders}`);

    // 9. 测试订单取消
    console.log('\n--- Test 9: Order Cancellation ---');
    const cancelOrderId = await ConsumerOrderService.syncPlatformOrder({
      tenant_id: tenantId,
      shop_id: shopId,
      platform: 'AMAZON',
      site: 'US',
      platform_order_id: 'TEST-2002',
      customer_name: 'Cancel Test',
      shipping_address: { city: 'Los Angeles', address: '456 Cancel St' },
      items: [{ sku: 'SKU-003', quantity: 1, price: 30 }],
      total_amount: 30,
      status: 'PAID'
    });
    
    await ConsumerOrderService.cancelOrder(tenantId, cancelOrderId, 'Test cancellation');
    const cancelledOrder = await db('cf_consumer_orders').where({ id: cancelOrderId }).first();
    console.log(`✅ Order cancelled, status: ${cancelledOrder.status}`);

    console.log('\n🎉 All tests completed successfully!');

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

testConsumerOrderService();
