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 { UserEntityMt, RoleMt } from '@d8d/user-module-mt';
import { FileMt } from '@d8d/file-module-mt';
import { SupplierMt } from '@d8d/supplier-module-mt';
import { MerchantMt } from '@d8d/merchant-module-mt';
import { adminGoodsRoutesMt } from '../../src/routes/index.mt';
import { GoodsMt, GoodsCategoryMt } from '../../src/entities/index.mt';
import { GoodsTestFactory } from '../factories/goods-test-factory';

// 设置集成测试钩子
setupIntegrationDatabaseHooksWithEntities([
  UserEntityMt, RoleMt, GoodsMt, GoodsCategoryMt, FileMt, SupplierMt, MerchantMt
])

describe('管理员商品管理API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof adminGoodsRoutesMt>>;
  let adminToken: string;
  let testUser: UserEntityMt;
  let testAdmin: UserEntityMt;
  let testCategory: GoodsCategoryMt;
  let testSupplier: SupplierMt;
  let testMerchant: MerchantMt;
  let testFactory: GoodsTestFactory;

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

    // 获取数据源并创建测试工厂
    const dataSource = await IntegrationTestDatabase.getDataSource();
    testFactory = new GoodsTestFactory(dataSource);

    // 使用测试工厂创建测试数据
    testUser = await testFactory.createTestUser();
    testAdmin = await testFactory.createTestAdmin();
    testCategory = await testFactory.createTestCategory(testUser.id);
    testSupplier = await testFactory.createTestSupplier(testUser.id);
    testMerchant = await testFactory.createTestMerchant(testUser.id);

    // 生成测试管理员的token
    adminToken = JWTUtil.generateToken({
      id: testAdmin.id,
      username: testAdmin.username,
      roles: [{name:'admin'}]
    });
  });

  describe('GET /goods', () => {
    it('应该返回所有商品列表', async () => {
      // 创建多个用户的商品
      const userGoods1 = await testFactory.createTestGoods(testUser.id, {
        name: '用户商品1',
        price: 100.00,
        costPrice: 80.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        stock: 100
      });

      const userGoods2 = await testFactory.createTestGoods(testAdmin.id, {
        name: '用户商品2',
        price: 200.00,
        costPrice: 160.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        stock: 50
      });

      const response = await client.index.$get({
        query: {}
      }, {
        headers: {
          'Authorization': `Bearer ${adminToken}`
        }
      });

      console.debug('管理员商品列表响应状态:', response.status);
      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);

        // 验证返回所有用户的商品（管理员可以访问所有数据）
        const userGoodsCount = data.data.filter((goods: any) => goods.createdBy === testUser.id).length;
        const adminGoodsCount = data.data.filter((goods: any) => goods.createdBy === testAdmin.id).length;

        expect(userGoodsCount).toBeGreaterThan(0);
        expect(adminGoodsCount).toBeGreaterThan(0);
      }
    });

    it('应该拒绝未认证用户的访问', async () => {
      const response = await client.index.$get({
        query: {}
      });
      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,
        createdBy: testUser.id // 管理员可以指定创建人
      };

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

      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 ${adminToken}`
        }
      });

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

  describe('GET /goods/:id', () => {
    it('应该返回指定商品的详情', async () => {
      // 先创建一个商品
      const testGoods = await testFactory.createTestGoods(testUser.id, {
        name: '测试商品详情',
        price: 100.00,
        costPrice: 80.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        stock: 100
      });

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

      console.debug('管理员商品详情响应状态:', response.status);
      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 response = await client[':id'].$get({
        param: { id: 999999 }
      }, {
        headers: {
          'Authorization': `Bearer ${adminToken}`
        }
      });

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

  describe('PUT /goods/:id', () => {
    it('应该成功更新任何商品', async () => {
      // 先创建一个商品
      const testGoods = await testFactory.createTestGoods(testUser.id, {
        name: '测试更新商品',
        price: 100.00,
        costPrice: 80.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        stock: 100
      });

      const updateData = {
        name: '管理员更新后的商品名称',
        price: 120.00,
        state: 2,
        updatedBy: testAdmin.id // 管理员可以指定更新人
      };

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

      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(testAdmin.id); // 验证可以指定更新人
      }
    });
  });

  describe('DELETE /goods/:id', () => {
    it('应该成功删除任何商品', async () => {
      // 先创建一个商品
      const testGoods = await testFactory.createTestGoods(testUser.id, {
        name: '测试删除商品',
        price: 100.00,
        costPrice: 80.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        stock: 100
      });

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

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

  describe('商品状态管理测试', () => {
    it('应该正确处理商品状态变更', async () => {
      // 创建可用状态的商品
      const activeGoods = await testFactory.createTestGoods(testUser.id, {
        name: '可用商品',
        price: 100.00,
        costPrice: 80.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        state: 1,
        stock: 100
      });

      // 创建不可用状态的商品
      const inactiveGoods = await testFactory.createTestGoods(testUser.id, {
        name: '不可用商品',
        price: 200.00,
        costPrice: 160.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        state: 2,
        stock: 50
      });

      // 验证状态过滤
      const response = await client.index.$get({
        query: { filters: JSON.stringify({ state: 1 }) }
      }, {
        headers: {
          'Authorization': `Bearer ${adminToken}`
        }
      });

      expect(response.status).toBe(200);
      const data = await response.json();

      // 类型检查确保data属性存在
      if ('data' in data && Array.isArray(data.data)) {
        // 应该只返回可用状态的商品
        const activeGoodsInResponse = data.data.filter((goods: any) => goods.state === 1);
        const inactiveGoodsInResponse = data.data.filter((goods: any) => goods.state === 2);

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

  describe('商品库存管理测试', () => {
    it('应该正确处理商品库存更新', async () => {
      // 创建一个商品
      const testGoods = await testFactory.createTestGoods(testUser.id, {
        name: '库存测试商品',
        price: 100.00,
        costPrice: 80.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        stock: 100
      });

      // 更新库存
      const updateData = {
        stock: 50
      };

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

      expect(response.status).toBe(200);

      if (response.status === 200) {
        const data = await response.json();
        expect(data.stock).toBe(Number(updateData.stock));
      }
    });
  });

  describe('管理员权限验证测试', () => {
    it('应该验证管理员可以访问所有数据', async () => {
      // 创建多个用户的商品
      const userGoods = await testFactory.createTestGoods(testUser.id, {
        name: '用户商品',
        price: 100.00,
        costPrice: 80.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        stock: 100
      });

      const adminGoods = await testFactory.createTestGoods(testAdmin.id, {
        name: '管理员商品',
        price: 200.00,
        costPrice: 160.00,
        categoryId1: testCategory.id,
        categoryId2: testCategory.id,
        categoryId3: testCategory.id,
        supplierId: testSupplier.id,
        merchantId: testMerchant.id,
        stock: 50
      });

      // 使用管理员token获取列表
      const response = await client.index.$get({
        query: {}
      }, {
        headers: {
          'Authorization': `Bearer ${adminToken}`
        }
      });

      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 adminGoodsInResponse = data.data.filter((goods: any) => goods.createdBy === testAdmin.id);

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