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 { adminGoodsCategoriesRoutes } from '../../src/routes/admin-goods-categories';
import { GoodsCategory } from '../../src/entities';

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

describe('管理员商品分类管理API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof adminGoodsCategoriesRoutes>>;
  let adminToken: string;
  let testUser: UserEntity;
  let testAdmin: UserEntity;

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

    // 获取数据源
    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);

    // 创建测试管理员用户
    testAdmin = userRepository.create({
      username: `test_admin_${Math.floor(Math.random() * 100000)}`,
      password: 'admin_password',
      nickname: '测试管理员',
      registrationSource: 'web'
    });
    await userRepository.save(testAdmin);

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

  describe('GET /goods-categories', () => {
    it('应该返回商品分类列表', async () => {
      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);
      }
    });

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

  describe('POST /goods-categories', () => {
    it('应该成功创建商品分类', async () => {
      const createData = {
        name: '管理员创建商品分类',
        parentId: 0,
        level: 1,
        state: 1
      };

      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.parentId).toBe(createData.parentId);
        expect(data.level).toBe(createData.level);
        expect(data.state).toBe(createData.state);
      }
    });

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

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

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

  describe('GET /goods-categories/:id', () => {
    it('应该返回指定商品分类的详情', async () => {
      // 先创建一个商品分类
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const categoryRepository = dataSource.getRepository(GoodsCategory);
      const testCategory = categoryRepository.create({
        name: '测试商品分类详情',
        parentId: 0,
        level: 1,
        state: 1,
        createdBy: testUser.id
      });
      await categoryRepository.save(testCategory);

      const response = await client[':id'].$get({
        param: { id: testCategory.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(testCategory.id);
        expect(data.name).toBe(testCategory.name);
        expect(data.parentId).toBe(testCategory.parentId);
        expect(data.level).toBe(testCategory.level);
        expect(data.state).toBe(testCategory.state);
      }
    });

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

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

  describe('PUT /goods-categories/:id', () => {
    it('应该成功更新商品分类', async () => {
      // 先创建一个商品分类
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const categoryRepository = dataSource.getRepository(GoodsCategory);
      const testCategory = categoryRepository.create({
        name: '测试更新商品分类',
        parentId: 0,
        level: 1,
        state: 1,
        createdBy: testUser.id
      });
      await categoryRepository.save(testCategory);

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

      const response = await client[':id'].$put({
        param: { id: testCategory.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.state).toBe(updateData.state);
      }
    });
  });

  describe('DELETE /goods-categories/:id', () => {
    it('应该成功删除商品分类', async () => {
      // 先创建一个商品分类
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const categoryRepository = dataSource.getRepository(GoodsCategory);
      const testCategory = categoryRepository.create({
        name: '测试删除商品分类',
        parentId: 0,
        level: 1,
        state: 1,
        createdBy: testUser.id
      });
      await categoryRepository.save(testCategory);

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

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

  describe('商品分类树形结构测试', () => {
    it('应该支持多级分类结构', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const categoryRepository = dataSource.getRepository(GoodsCategory);

      // 创建一级分类
      const level1Category = categoryRepository.create({
        name: '一级分类',
        parentId: 0,
        level: 1,
        state: 1,
        createdBy: testUser.id
      });
      await categoryRepository.save(level1Category);

      // 创建二级分类
      const level2Category = categoryRepository.create({
        name: '二级分类',
        parentId: level1Category.id,
        level: 2,
        state: 1,
        createdBy: testUser.id
      });
      await categoryRepository.save(level2Category);

      // 创建三级分类
      const level3Category = categoryRepository.create({
        name: '三级分类',
        parentId: level2Category.id,
        level: 3,
        state: 1,
        createdBy: testUser.id
      });
      await categoryRepository.save(level3Category);

      // 验证分类层级关系
      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)) {
        // 验证分类数量
        expect(data.data.length).toBeGreaterThanOrEqual(3);
      } else {
        // 如果响应是错误格式，应该失败
        expect(data).toHaveProperty('data');
      }
    });
  });

  describe('商品分类状态管理测试', () => {
    it('应该正确处理分类状态变更', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const categoryRepository = dataSource.getRepository(GoodsCategory);

      // 创建可用状态的分类
      const activeCategory = categoryRepository.create({
        name: '可用分类',
        parentId: 0,
        level: 1,
        state: 1,
        createdBy: testUser.id
      });
      await categoryRepository.save(activeCategory);

      // 创建不可用状态的分类
      const inactiveCategory = categoryRepository.create({
        name: '不可用分类',
        parentId: 0,
        level: 1,
        state: 2,
        createdBy: testUser.id
      });
      await categoryRepository.save(inactiveCategory);

      // 验证状态过滤
      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 activeCategories = data.data.filter((category: any) => category.state === 1);
        expect(activeCategories.length).toBeGreaterThan(0);

        const inactiveCategories = data.data.filter((category: any) => category.state === 2);
        expect(inactiveCategories.length).toBe(0);
      } else {
        // 如果响应是错误格式，应该失败
        expect(data).toHaveProperty('data');
      }
    });
  });
});