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

import { ProductManagementMockDataSource } from '../productManagementDataSource';
import { ProductManagementStatus } from '../../types/productManagement';

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

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

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

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

    it('应该根据关键词筛选商品', async () => {
      const result = await dataSource.listProducts({
        keyword: '温度传感器',
        field: 'name',
        order: null
      });

      expect(result.data.length).toBeGreaterThan(0);
      expect(result.data[0].name).toContain('温度传感器');
    });

    it('应该根据平台筛选商品', async () => {
      const result = await dataSource.listProducts({
        platform: ['Amazon'],
        field: 'name',
        order: null
      });

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

    it('应该根据店铺筛选商品', async () => {
      const shops = await dataSource.getShops();
      const amazonShop = shops.find(s => s.platform === 'Amazon');
      
      if (amazonShop) {
        const result = await dataSource.listProducts({
          shop: [amazonShop.id],
          field: 'name',
          order: null
        });

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

    it('应该根据状态筛选商品', async () => {
      const result = await dataSource.listProducts({
        status: ['LIVE'],
        field: 'name',
        order: null
      });

      expect(result.data.length).toBeGreaterThan(0);
      expect(result.data.every(p => p.managementStatus === 'LIVE')).toBe(true);
    });

    it('应该支持价格范围筛选', async () => {
      const result = await dataSource.listProducts({
        priceRange: [50, 100],
        field: 'name',
        order: null
      });

      expect(result.data.length).toBeGreaterThan(0);
      expect(result.data.every(p => p.price >= 50 && p.price <= 100)).toBe(true);
    });

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

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

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

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

  describe('getProduct', () => {
    it('应该返回正确的商品详情', async () => {
      const products = await dataSource.listProducts({
        field: 'name',
        order: null
      });
      
      if (products.data.length > 0) {
        const product = await dataSource.getProduct(products.data[0].id);
        expect(product).toBeDefined();
        expect(product?.id).toBe(products.data[0].id);
      }
    });

    it('应该返回null当商品不存在', async () => {
      const product = await dataSource.getProduct('non-existent-id');
      expect(product).toBeNull();
    });
  });

  describe('updateProductStatus', () => {
    it('应该成功更新商品状态', async () => {
      const products = await dataSource.listProducts({
        field: 'name',
        order: null
      });
      
      if (products.data.length > 0) {
        const newStatus: ProductManagementStatus = 'OFFLINE';
        const updatedProduct = await dataSource.updateProductStatus(products.data[0].id, newStatus);
        
        expect(updatedProduct).toBeDefined();
        expect(updatedProduct?.managementStatus).toBe(newStatus);
        expect(updatedProduct?.updatedAt).not.toBe(products.data[0].updatedAt);
      }
    });

    it('应该返回null当商品不存在', async () => {
      const result = await dataSource.updateProductStatus('non-existent-id', 'OFFLINE');
      expect(result).toBeNull();
    });
  });

  describe('batchUpdateProducts', () => {
    it('应该成功批量更新商品', async () => {
      const products = await dataSource.listProducts({
        field: 'name',
        order: null
      });
      
      if (products.data.length >= 2) {
        const productIds = products.data.slice(0, 2).map(p => p.id);
        const updates = { price: 99.99 };
        
        const count = await dataSource.batchUpdateProducts(productIds, updates);
        
        expect(count).toBe(2);
        
        // 验证更新结果
        for (const productId of productIds) {
          const updatedProduct = await dataSource.getProduct(productId);
          expect(updatedProduct?.price).toBe(99.99);
        }
      }
    });
  });

  describe('batchDeleteProducts', () => {
    it('应该成功批量删除商品', async () => {
      const products = await dataSource.listProducts({
        field: 'name',
        order: null
      });
      
      if (products.data.length >= 2) {
        const productIds = products.data.slice(0, 2).map(p => p.id);
        const originalCount = products.total;
        
        const count = await dataSource.batchDeleteProducts(productIds);
        
        expect(count).toBe(2);
        
        // 验证删除结果
        const remainingProducts = await dataSource.listProducts({
          field: 'name',
          order: null
        });
        
        expect(remainingProducts.total).toBe(originalCount - 2);
      }
    });
  });

  describe('getProductStatistics', () => {
    it('应该返回正确的统计信息', async () => {
      const statistics = await dataSource.getProductStatistics();
      
      expect(statistics.totalProducts).toBeGreaterThanOrEqual(0);
      expect(statistics.draft).toBeGreaterThanOrEqual(0);
      expect(statistics.priced).toBeGreaterThanOrEqual(0);
      expect(statistics.listed).toBeGreaterThanOrEqual(0);
      expect(statistics.live).toBeGreaterThanOrEqual(0);
      expect(statistics.offline).toBeGreaterThanOrEqual(0);
      expect(statistics.totalValue).toBeGreaterThanOrEqual(0);
      expect(statistics.totalProfit).toBeGreaterThanOrEqual(0);
    });

    it('应该支持日期范围统计', async () => {
      const statistics = await dataSource.getProductStatistics({
        startDate: '2026-01-01T00:00:00Z',
        endDate: '2026-12-31T23:59:59Z'
      });
      
      expect(statistics.totalProducts).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('getCategories', () => {
    it('应该返回所有分类', async () => {
      const categories = await dataSource.getCategories();
      
      expect(categories.length).toBeGreaterThan(0);
      expect(categories.every(category => typeof category === 'string')).toBe(true);
    });
  });

  describe('业务逻辑集中化验证', () => {
    it('所有筛选逻辑应该集中在数据源层', async () => {
      // 验证筛选逻辑在数据源层实现，而不是在UI层
      const complexFilter = {
        keyword: '传感器',
        platform: ['Amazon', 'TikTok'],
        status: ['LIVE', 'LISTED'],
        priceRange: [50, 200] as [number, number],
        field: 'price',
        order: 'ascend' as const
      };

      const result = await dataSource.listProducts(complexFilter);
      
      // 验证筛选结果符合预期
      expect(result.data.every(p => 
        p.name.toLowerCase().includes('传感器') &&
        ['Amazon', 'TikTok'].includes(p.platform) &&
        ['LIVE', 'LISTED'].includes(p.managementStatus) &&
        p.price >= 50 && p.price <= 200
      )).toBe(true);
      
      // 验证排序正确
      for (let i = 0; i < result.data.length - 1; i++) {
        expect(result.data[i].price).toBeLessThanOrEqual(result.data[i + 1].price);
      }
    });

    it('统计计算逻辑应该集中在数据源层', async () => {
      const result = await dataSource.listProducts({
        field: 'name',
        order: null
      });
      
      // 验证统计信息计算正确
      const expectedDraft = result.data.filter(p => p.managementStatus === 'DRAFT').length;
      const expectedLive = result.data.filter(p => p.managementStatus === 'LIVE').length;
      const expectedTotalValue = result.data.reduce((sum, p) => sum + p.price * p.stock, 0);
      const expectedTotalProfit = result.data.reduce((sum, p) => sum + (p.profit || 0), 0);
      
      expect(result.statistics.draft).toBe(expectedDraft);
      expect(result.statistics.live).toBe(expectedLive);
      expect(result.statistics.totalValue).toBe(expectedTotalValue);
      expect(result.statistics.totalProfit).toBe(expectedTotalProfit);
    });
  });
});