/**
 * [BE-O001] 订单管理数据源单元测试
 * 测试数据源抽象层的业务逻辑正确性
 * AI注意: 这是单元测试，验证业务逻辑集中化原则的实现
 */

import { OrderManagementMockDataSource } from '../orderManagementDataSource';
import { OrderStatus } from '../../types/order';

describe('OrderManagementMockDataSource', () => {
  let dataSource: OrderManagementMockDataSource;

  beforeEach(() => {
    dataSource = new OrderManagementMockDataSource();
  });

  describe('listOrders', () => {
    it('应该返回所有订单当没有筛选条件', async () => {
      const result = await dataSource.listOrders({
        field: 'orderNumber',
        order: null
      });

      expect(result.data).toHaveLength(1); // 根据Mock数据调整
      expect(result.total).toBeGreaterThan(0);
      expect(result.statistics.totalOrders).toBeGreaterThan(0);
    });

    it('应该根据订单号筛选订单', async () => {
      const result = await dataSource.listOrders({
        keyword: 'TK',
        field: 'orderNumber',
        order: null
      });

      expect(result.data.length).toBeGreaterThan(0);
      expect(result.data[0].orderNumber).toContain('TK');
    });

    it('应该根据平台筛选订单', async () => {
      const result = await dataSource.listOrders({
        platform: ['TikTok'],
        field: 'orderNumber',
        order: null
      });

      expect(result.data.length).toBeGreaterThan(0);
      expect(result.data.every(o => o.platform === 'TikTok')).toBe(true);
    });

    it('应该根据店铺筛选订单', async () => {
      const shops = await dataSource.getShops();
      const tiktokShop = shops.find(s => s.platform === 'TikTok');
      
      if (tiktokShop) {
        const result = await dataSource.listOrders({
          shop: [tiktokShop.id],
          field: 'orderNumber',
          order: null
        });

        expect(result.data.length).toBeGreaterThan(0);
        expect(result.data.every(o => o.shopId === tiktokShop.id)).toBe(true);
      }
    });

    it('应该根据状态筛选订单', async () => {
      const result = await dataSource.listOrders({
        status: ['pending'],
        field: 'orderNumber',
        order: null
      });

      expect(result.data.length).toBeGreaterThan(0);
      expect(result.data.every(o => o.status === 'pending')).toBe(true);
    });

    it('应该支持金额范围筛选', async () => {
      const result = await dataSource.listOrders({
        amountRange: [100, 500],
        field: 'orderNumber',
        order: null
      });

      expect(result.data.length).toBeGreaterThan(0);
      expect(result.data.every(o => o.totalAmount >= 100 && o.totalAmount <= 500)).toBe(true);
    });

    it('应该支持日期范围筛选', async () => {
      const result = await dataSource.listOrders({
        dateRange: ['2026-01-01T00:00:00Z', '2026-12-31T23:59:59Z'],
        field: 'orderNumber',
        order: null
      });

      expect(result.data.length).toBeGreaterThan(0);
    });

    it('应该支持排序', async () => {
      const result = await dataSource.listOrders({
        field: 'totalAmount',
        order: 'ascend'
      });

      expect(result.data.length).toBeGreaterThan(0);
      
      // 检查金额是否按升序排列
      for (let i = 0; i < result.data.length - 1; i++) {
        expect(result.data[i].totalAmount).toBeLessThanOrEqual(result.data[i + 1].totalAmount);
      }
    });

    it('应该支持分页', async () => {
      const result = await dataSource.listOrders({
        page: 1,
        pageSize: 5,
        field: 'orderNumber',
        order: null
      });

      expect(result.data.length).toBeLessThanOrEqual(5);
      expect(result.total).toBeGreaterThan(0);
    });
  });

  describe('getOrder', () => {
    it('应该返回正确的订单详情', async () => {
      const orders = await dataSource.listOrders({
        field: 'orderNumber',
        order: null
      });
      
      if (orders.data.length > 0) {
        const order = await dataSource.getOrder(orders.data[0].id);
        expect(order).toBeDefined();
        expect(order?.id).toBe(orders.data[0].id);
      }
    });

    it('应该返回null当订单不存在', async () => {
      const order = await dataSource.getOrder('non-existent-id');
      expect(order).toBeNull();
    });
  });

  describe('updateOrderStatus', () => {
    it('应该成功更新订单状态', async () => {
      const orders = await dataSource.listOrders({
        field: 'orderNumber',
        order: null
      });
      
      if (orders.data.length > 0) {
        const newStatus: OrderStatus = 'confirmed';
        const updatedOrder = await dataSource.updateOrderStatus(orders.data[0].id, newStatus);
        
        expect(updatedOrder).toBeDefined();
        expect(updatedOrder?.status).toBe(newStatus);
        expect(updatedOrder?.updatedAt).not.toBe(orders.data[0].updatedAt);
      }
    });

    it('应该返回null当订单不存在', async () => {
      const result = await dataSource.updateOrderStatus('non-existent-id', 'confirmed');
      expect(result).toBeNull();
    });
  });

  describe('batchConfirmOrders', () => {
    it('应该成功批量确认订单', async () => {
      const orders = await dataSource.listOrders({
        field: 'orderNumber',
        order: null
      });
      
      if (orders.data.length >= 2) {
        const orderIds = orders.data.slice(0, 2).map(o => o.id);
        
        const count = await dataSource.batchConfirmOrders(orderIds);
        
        expect(count).toBe(2);
        
        // 验证更新结果
        for (const orderId of orderIds) {
          const updatedOrder = await dataSource.getOrder(orderId);
          expect(updatedOrder?.status).toBe('confirmed');
        }
      }
    });
  });

  describe('batchShipOrders', () => {
    it('应该成功批量发货订单', async () => {
      const orders = await dataSource.listOrders({
        field: 'orderNumber',
        order: null
      });
      
      if (orders.data.length >= 2) {
        const orderIds = orders.data.slice(0, 2).map(o => o.id);
        const trackingInfo = {
          trackingNumber: 'TRK123456789',
          carrier: '顺丰速运'
        };
        
        const count = await dataSource.batchShipOrders(orderIds, trackingInfo);
        
        expect(count).toBe(2);
        
        // 验证更新结果
        for (const orderId of orderIds) {
          const updatedOrder = await dataSource.getOrder(orderId);
          expect(updatedOrder?.status).toBe('shipped');
          expect(updatedOrder?.trackingNumber).toBe(trackingInfo.trackingNumber);
          expect(updatedOrder?.carrier).toBe(trackingInfo.carrier);
        }
      }
    });
  });

  describe('batchCancelOrders', () => {
    it('应该成功批量取消订单', async () => {
      const orders = await dataSource.listOrders({
        field: 'orderNumber',
        order: null
      });
      
      if (orders.data.length >= 2) {
        const orderIds = orders.data.slice(0, 2).map(o => o.id);
        const reason = '客户取消订单';
        
        const count = await dataSource.batchCancelOrders(orderIds, reason);
        
        expect(count).toBe(2);
        
        // 验证更新结果
        for (const orderId of orderIds) {
          const updatedOrder = await dataSource.getOrder(orderId);
          expect(updatedOrder?.status).toBe('cancelled');
          expect(updatedOrder?.cancelReason).toBe(reason);
        }
      }
    });
  });

  describe('getOrderStatistics', () => {
    it('应该返回正确的统计信息', async () => {
      const statistics = await dataSource.getOrderStatistics();
      
      expect(statistics.totalOrders).toBeGreaterThanOrEqual(0);
      expect(statistics.pending).toBeGreaterThanOrEqual(0);
      expect(statistics.confirmed).toBeGreaterThanOrEqual(0);
      expect(statistics.shipped).toBeGreaterThanOrEqual(0);
      expect(statistics.delivered).toBeGreaterThanOrEqual(0);
      expect(statistics.cancelled).toBeGreaterThanOrEqual(0);
      expect(statistics.totalAmount).toBeGreaterThanOrEqual(0);
      expect(statistics.averageAmount).toBeGreaterThanOrEqual(0);
    });

    it('应该支持日期范围统计', async () => {
      const statistics = await dataSource.getOrderStatistics({
        startDate: '2026-01-01T00:00:00Z',
        endDate: '2026-12-31T23:59:59Z'
      });
      
      expect(statistics.totalOrders).toBeGreaterThanOrEqual(0);
    });
  });

  describe('getShops', () => {
    it('应该返回所有店铺', async () => {
      const shops = await dataSource.getShops();
      
      expect(shops.length).toBeGreaterThan(0);
      expect(shops.every(shop => 
        shop.id && shop.name && shop.platform && shop.status && shop.region && shop.currency
      )).toBe(true);
    });
  });

  describe('业务逻辑集中化验证', () => {
    it('所有筛选逻辑应该集中在数据源层', async () => {
      // 验证筛选逻辑在数据源层实现，而不是在UI层
      const complexFilter = {
        keyword: 'TK',
        platform: ['TikTok', 'Shopee'],
        status: ['pending', 'confirmed'],
        amountRange: [100, 500] as [number, number],
        dateRange: ['2026-01-01T00:00:00Z', '2026-12-31T23:59:59Z'] as [string, string],
        field: 'totalAmount',
        order: 'ascend' as const
      };

      const result = await dataSource.listOrders(complexFilter);
      
      // 验证筛选结果符合预期
      if (result.data.length > 0) {
        expect(result.data.every(o => 
          o.orderNumber.includes('TK') &&
          ['TikTok', 'Shopee'].includes(o.platform) &&
          ['pending', 'confirmed'].includes(o.status) &&
          o.totalAmount >= 100 && o.totalAmount <= 500
        )).toBe(true);
        
        // 验证排序正确
        for (let i = 0; i < result.data.length - 1; i++) {
          expect(result.data[i].totalAmount).toBeLessThanOrEqual(result.data[i + 1].totalAmount);
        }
      }
    });

    it('统计计算逻辑应该集中在数据源层', async () => {
      const result = await dataSource.listOrders({
        field: 'orderNumber',
        order: null
      });
      
      // 验证统计信息计算正确
      const expectedPending = result.data.filter(o => o.status === 'pending').length;
      const expectedConfirmed = result.data.filter(o => o.status === 'confirmed').length;
      const expectedTotalAmount = result.data.reduce((sum, o) => sum + o.totalAmount, 0);
      const expectedAverageAmount = result.data.length > 0 ? expectedTotalAmount / result.data.length : 0;
      
      expect(result.statistics.pending).toBe(expectedPending);
      expect(result.statistics.confirmed).toBe(expectedConfirmed);
      expect(result.statistics.totalAmount).toBe(expectedTotalAmount);
      expect(result.statistics.averageAmount).toBe(expectedAverageAmount);
    });

    it('批量操作逻辑应该集中在数据源层', async () => {
      const orders = await dataSource.listOrders({
        field: 'orderNumber',
        order: null
      });
      
      if (orders.data.length >= 2) {
        const orderIds = orders.data.slice(0, 2).map(o => o.id);
        
        // 批量确认订单
        const confirmCount = await dataSource.batchConfirmOrders(orderIds);
        expect(confirmCount).toBe(2);
        
        // 验证状态更新
        for (const orderId of orderIds) {
          const updatedOrder = await dataSource.getOrder(orderId);
          expect(updatedOrder?.status).toBe('confirmed');
        }
      }
    });
  });

  describe('错误处理验证', () => {
    it('应该正确处理不存在的订单', async () => {
      const nonExistentOrder = await dataSource.getOrder('non-existent-id');
      expect(nonExistentOrder).toBeNull();
      
      const updateResult = await dataSource.updateOrderStatus('non-existent-id', 'confirmed');
      expect(updateResult).toBeNull();
      
      const batchResult = await dataSource.batchConfirmOrders(['non-existent-id']);
      expect(batchResult).toBe(0);
    });

    it('应该正确处理空批量操作', async () => {
      const emptyBatchResult = await dataSource.batchConfirmOrders([]);
      expect(emptyBatchResult).toBe(0);
    });
  });
});