import { describe, it, expect, beforeEach } from 'vitest';
import { testClient } from 'hono/testing';
import { IntegrationTestDatabase, setupIntegrationDatabaseHooksWithEntities } from '@d8d/shared-test-util';
import { JWTUtil } from '@d8d/shared-utils';
import { UserEntity, Role } from '@d8d/user-module';
import { File } from '@d8d/file-module';
import { Supplier } from '@d8d/supplier-module';
import { Merchant } from '@d8d/merchant-module';
import { userGoodsRoutes } from '../../src/routes';
import { Goods, GoodsCategory } from '../../src/entities';

// 设置集成测试钩子
setupIntegrationDatabaseHooksWithEntities([
  UserEntity, Role, Goods, GoodsCategory, File, Supplier, Merchant
])

describe('用户商品管理API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof userGoodsRoutes>>;
  let userToken: string;
  let otherUserToken: string;
  let testUser: UserEntity;
  let otherUser: UserEntity;
  let testCategory: GoodsCategory;
  let testSupplier: Supplier;
  let testMerchant: Merchant;
  let testFile: File;

  beforeEach(async () => {
    // 创建测试客户端
    client = testClient(userGoodsRoutes);

    // 获取数据源
    const dataSource = await IntegrationTestDatabase.getDataSource();

    // 创建测试用户
    const userRepository = dataSource.getRepository(UserEntity);
    testUser = userRepository.create({
      username: `test_user_${Math.floor(Math.random() * 100000)}`,
      password: 'test_password',
      nickname: '测试用户',
      registrationSource: 'web'
    });
    await userRepository.save(testUser);

    // 创建其他用户
    otherUser = userRepository.create({
      username: `other_user_${Math.floor(Math.random() * 100000)}`,
      password: 'other_password',
      nickname: '其他用户',
      registrationSource: 'web'
    });
    await userRepository.save(otherUser);

    // 生成测试用户的token
    userToken = JWTUtil.generateToken({
      id: testUser.id,
      username: testUser.username,
      roles: [{name:'user'}]
    });

    // 生成其他用户的token
    otherUserToken = JWTUtil.generateToken({
      id: otherUser.id,
      username: otherUser.username,
      roles: [{name:'user'}]
    });

    // 创建测试商品分类
    const categoryRepository = dataSource.getRepository(GoodsCategory);
    testCategory = categoryRepository.create({
      name: '测试分类',
      parentId: 0,
      level: 1,
      state: 1,
      createdBy: testUser.id
    });
    await categoryRepository.save(testCategory);

    // 创建测试供应商
    const supplierRepository = dataSource.getRepository(Supplier);
    testSupplier = supplierRepository.create({
      name: '测试供应商',
      username: `test_supplier_${Math.floor(Math.random() * 100000)}`,
      password: 'password123',
      phone: '13800138000',
      realname: '测试供应商',
      state: 1,
      createdBy: testUser.id
    });
    await supplierRepository.save(testSupplier);

    // 创建测试商户
    const merchantRepository = dataSource.getRepository(Merchant);
    testMerchant = merchantRepository.create({
      name: '测试商户',
      username: `test_merchant_${Math.floor(Math.random() * 100000)}`,
      password: 'password123',
      phone: '13800138001',
      realname: '测试商户',
      state: 1,
      createdBy: testUser.id
    });
    await merchantRepository.save(testMerchant);

    // 创建测试文件
    const fileRepository = dataSource.getRepository(File);
    testFile = fileRepository.create({
      name: 'test_image.jpg',
      type: 'image/jpeg',
      size: 102400,
      path: 'images/test_image.jpg',
      uploadUserId: testUser.id,
      uploadTime: new Date(),
      createdAt: new Date(),
      updatedAt: new Date()
    });
    await fileRepository.save(testFile);
  });

  describe('GET /goods', () => {
    it('应该返回当前用户的商品列表', async () => {
      // 为测试用户创建一些商品
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const goodsRepository = dataSource.getRepository(Goods);

      const userGoods1 = goodsRepository.create({
        name: '用户商品1',
        price: 100.00,
        costPrice: 80.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        goodsType: 1,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        imageFileId: testFile.id,
        state: 1,
        stock: 100,
        lowestBuy: 1,
        createdBy: testUser.id
      });
      await goodsRepository.save(userGoods1);

      const userGoods2 = goodsRepository.create({
        name: '用户商品2',
        price: 200.00,
        costPrice: 160.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        goodsType: 1,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        imageFileId: testFile.id,
        state: 1,
        stock: 50,
        lowestBuy: 1,
        createdBy: testUser.id
      });
      await goodsRepository.save(userGoods2);

      // 为其他用户创建一个商品，确保不会返回
      const otherUserGoods = goodsRepository.create({
        name: '其他用户商品',
        price: 300.00,
        costPrice: 240.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        goodsType: 1,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        imageFileId: testFile.id,
        state: 1,
        stock: 30,
        lowestBuy: 1,
        createdBy: otherUser.id
      });
      await goodsRepository.save(otherUserGoods);

      const response = await client.index.$get({
        query: {
          page: 1,
          pageSize: 10
        }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      console.debug('用户商品列表响应状态:', response.status);
      if (response.status !== 200) {
        const errorData = await response.json();
        console.debug('用户商品列表错误响应:', errorData);
      }
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const data = await response.json();
        expect(data).toHaveProperty('data');
        expect(Array.isArray(data.data)).toBe(true);

        // 验证只返回当前用户的商品
        data.data.forEach((goods: any) => {
          expect(goods.createdBy).toBe(testUser.id);
        });

        // 验证不包含其他用户的商品
        const otherUserGoodsInResponse = data.data.find((goods: any) => goods.createdBy === otherUser.id);
        expect(otherUserGoodsInResponse).toBeUndefined();
      }
    });

    it('应该拒绝未认证用户的访问', async () => {
      const response = await client.index.$get({
        query: {
          page: 1,
          pageSize: 10
        }
      });
      expect(response.status).toBe(401);
    });
  });

  describe('POST /goods', () => {
    it('应该成功创建商品并自动设置当前用户权限', async () => {
      const createData = {
        name: '用户创建商品',
        price: 150.00,
        costPrice: 120.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        goodsType: 1,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        state: 1,
        stock: 80,
        lowestBuy: 1
      };

      const response = await client.index.$post({
        json: createData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      console.debug('用户创建商品响应状态:', response.status);
      if (response.status !== 201) {
        const errorData = await response.json();
        console.debug('用户创建商品错误响应:', errorData);
      }
      expect(response.status).toBe(201);

      if (response.status === 201) {
        const data = await response.json();
        expect(data).toHaveProperty('id');
        expect(data.name).toBe(createData.name);
        expect(data.price).toBe(Number(createData.price));
        expect(data.createdBy).toBe(testUser.id); // 验证自动设置当前用户权限
      }
    });

    it('应该验证创建商品的必填字段', async () => {
      const invalidData = {
        // 缺少必填字段
        name: '',
        price: -1,
        categoryId1: -1
      };

      const response = await client.index.$post({
        json: invalidData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(response.status).toBe(400);
    });
  });

  describe('GET /goods/:id', () => {
    it('应该返回当前用户的商品详情', async () => {
      // 先为测试用户创建一个商品
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const goodsRepository = dataSource.getRepository(Goods);
      const testGoods = goodsRepository.create({
        name: '测试用户商品详情',
        price: 100.00,
        costPrice: 80.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        goodsType: 1,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        state: 1,
        stock: 100,
        lowestBuy: 1,
        createdBy: testUser.id
      });
      await goodsRepository.save(testGoods);

      const response = await client[':id'].$get({
        param: { id: testGoods.id }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      console.debug('用户商品详情响应状态:', response.status);
      if (response.status !== 200) {
        const errorData = await response.json();
        console.debug('用户商品详情错误响应:', errorData);
      }
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const data = await response.json();
        expect(data.id).toBe(testGoods.id);
        expect(data.name).toBe(testGoods.name);
        expect(data.createdBy).toBe(testUser.id);
      }
    });

    it('应该拒绝访问其他用户的商品', async () => {
      // 为其他用户创建一个商品
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const goodsRepository = dataSource.getRepository(Goods);
      const otherUserGoods = goodsRepository.create({
        name: '其他用户商品',
        price: 100.00,
        costPrice: 80.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        goodsType: 1,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        state: 1,
        stock: 100,
        lowestBuy: 1,
        createdBy: otherUser.id
      });
      await goodsRepository.save(otherUserGoods);

      const response = await client[':id'].$get({
        param: { id: otherUserGoods.id }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(response.status).toBe(403); // 数据权限控制返回403（权限不足）
    });

    it('应该处理不存在的商品', async () => {
      const response = await client[':id'].$get({
        param: { id: 999999 }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(response.status).toBe(404);
    });
  });

  describe('PUT /goods/:id', () => {
    it('应该成功更新当前用户的商品', async () => {
      // 先为测试用户创建一个商品
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const goodsRepository = dataSource.getRepository(Goods);
      const testGoods = goodsRepository.create({
        name: '测试更新商品',
        price: 100.00,
        costPrice: 80.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        goodsType: 1,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        state: 1,
        stock: 100,
        lowestBuy: 1,
        createdBy: testUser.id
      });
      await goodsRepository.save(testGoods);

      const updateData = {
        name: '更新后的商品名称',
        price: 120.00,
        state: 2
      };

      const response = await client[':id'].$put({
        param: { id: testGoods.id },
        json: updateData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      console.debug('用户更新商品响应状态:', response.status);
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const data = await response.json();
        expect(data.name).toBe(updateData.name);
        expect(data.price).toBe(Number(updateData.price));
        expect(data.state).toBe(updateData.state);
        expect(data.updatedBy).toBe(testUser.id); // 验证自动设置更新用户
      }
    });

    it('应该拒绝更新其他用户的商品', async () => {
      // 为其他用户创建一个商品
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const goodsRepository = dataSource.getRepository(Goods);
      const otherUserGoods = goodsRepository.create({
        name: '其他用户商品',
        price: 100.00,
        costPrice: 80.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        goodsType: 1,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        state: 1,
        stock: 100,
        lowestBuy: 1,
        createdBy: otherUser.id
      });
      await goodsRepository.save(otherUserGoods);

      const updateData = {
        name: '尝试更新其他用户商品'
      };

      const response = await client[':id'].$put({
        param: { id: otherUserGoods.id },
        json: updateData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(response.status).toBe(403); // 数据权限控制返回403
    });
  });

  describe('DELETE /goods/:id', () => {
    it('应该成功删除当前用户的商品', async () => {
      // 先为测试用户创建一个商品
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const goodsRepository = dataSource.getRepository(Goods);
      const testGoods = goodsRepository.create({
        name: '测试删除商品',
        price: 100.00,
        costPrice: 80.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        goodsType: 1,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        state: 1,
        stock: 100,
        lowestBuy: 1,
        createdBy: testUser.id
      });
      await goodsRepository.save(testGoods);

      const response = await client[':id'].$delete({
        param: { id: testGoods.id }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      console.debug('用户删除商品响应状态:', response.status);
      expect(response.status).toBe(204);
    });

    it('应该拒绝删除其他用户的商品', async () => {
      // 为其他用户创建一个商品
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const goodsRepository = dataSource.getRepository(Goods);
      const otherUserGoods = goodsRepository.create({
        name: '其他用户商品',
        price: 100.00,
        costPrice: 80.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        goodsType: 1,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        state: 1,
        stock: 100,
        lowestBuy: 1,
        createdBy: otherUser.id
      });
      await goodsRepository.save(otherUserGoods);

      const response = await client[':id'].$delete({
        param: { id: otherUserGoods.id }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(response.status).toBe(403); // 数据权限控制返回403
    });
  });

  describe('数据权限配置测试', () => {
    it('应该验证dataPermission配置正确工作', async () => {
      // 这个测试验证数据权限配置是否正常工作
      // 用户只能访问自己创建的商品

      const dataSource = await IntegrationTestDatabase.getDataSource();
      const goodsRepository = dataSource.getRepository(Goods);

      // 创建测试用户和其他用户的商品
      const userGoods = goodsRepository.create({
        name: '用户商品',
        price: 100.00,
        costPrice: 80.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        goodsType: 1,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        state: 1,
        stock: 100,
        lowestBuy: 1,
        createdBy: testUser.id
      });
      await goodsRepository.save(userGoods);

      const otherUserGoods = goodsRepository.create({
        name: '其他用户商品',
        price: 200.00,
        costPrice: 160.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        goodsType: 1,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        state: 1,
        stock: 50,
        lowestBuy: 1,
        createdBy: otherUser.id
      });
      await goodsRepository.save(otherUserGoods);

      // 使用测试用户token获取列表
      const response = await client.index.$get({
        query: {
          page: 1,
          pageSize: 10
        }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      if (response.status !== 200) {
        const errorData = await response.json();
        console.debug('数据权限配置测试错误响应:', errorData);
      }
      expect(response.status).toBe(200);
      const data = await response.json();

      // 类型检查确保data属性存在
      if ('data' in data && Array.isArray(data.data)) {
        // 验证只返回测试用户的商品
        const userGoodsInResponse = data.data.filter((goods: any) => goods.createdBy === testUser.id);
        const otherUserGoodsInResponse = data.data.filter((goods: any) => goods.createdBy === otherUser.id);

        expect(userGoodsInResponse.length).toBeGreaterThan(0);
        expect(otherUserGoodsInResponse.length).toBe(0);
      } else {
        // 如果响应是错误格式，应该失败
        expect(data).toHaveProperty('data');
      }
    });
  });
});