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 platformRoutes from '../../src/routes/platform.routes';
import { Platform } from '../../src/entities/platform.entity';

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

describe('平台管理API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof platformRoutes>>;
  let testToken: string;
  let testUser: UserEntity;

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

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

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

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

  describe('POST /platform/createPlatform', () => {
    it('应该成功创建平台', async () => {
      const createData = {
        platformName: '微信平台',
        contactPerson: '张三',
        contactPhone: '13800138000',
        contactEmail: 'zhangsan@example.com'
      };

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

      console.debug('创建平台响应状态:', response.status);
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const data = await response.json();
        expect(data.platformName).toBe(createData.platformName);
        expect(data.contactPerson).toBe(createData.contactPerson);
        expect(data.contactPhone).toBe(createData.contactPhone);
      }
    });

    it('应该验证平台名称重复', async () => {
      // 先创建一个平台
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const platformRepository = dataSource.getRepository(Platform);
      const existingPlatform = platformRepository.create({
        platformName: '微信平台',
        contactPerson: '张三',
        contactPhone: '13800138000',
        status: 1
      });
      await platformRepository.save(existingPlatform);

      // 尝试创建同名平台
      const createData = {
        platformName: '微信平台', // 重复的名称
        contactPerson: '李四',
        contactPhone: '13900139000'
      };

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

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

    it('应该验证必填字段', async () => {
      const createData = {
        platformName: '', // 空字符串，应该验证失败
        contactPerson: '张三',
        contactPhone: '13800138000'
      };

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

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

  describe('POST /platform/deletePlatform', () => {
    it('应该成功删除平台（软删除）', async () => {
      // 先创建一个平台
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const platformRepository = dataSource.getRepository(Platform);
      const platform = platformRepository.create({
        platformName: '测试删除平台',
        contactPerson: '张三',
        contactPhone: '13800138000',
        status: 1
      });
      await platformRepository.save(platform);

      const deleteData = {
        id: platform.id
      };

      const response = await client.deletePlatform.$post({
        json: deleteData
      }, {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

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

      if (response.status === 200) {
        const data = await response.json();
        expect(data.success).toBe(true);

        // 验证平台状态已改为0（软删除）
        const deletedPlatform = await platformRepository.findOne({ where: { id: platform.id } });
        expect(deletedPlatform?.status).toBe(0);
      }
    });

    it('应该处理不存在的平台ID', async () => {
      const deleteData = {
        id: 99999 // 不存在的ID
      };

      const response = await client.deletePlatform.$post({
        json: deleteData
      }, {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(200); // 删除不存在的平台也返回成功（软删除逻辑）
    });
  });

  describe('POST /platform/updatePlatform', () => {
    it('应该成功更新平台', async () => {
      // 先创建一个平台
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const platformRepository = dataSource.getRepository(Platform);
      const platform = platformRepository.create({
        platformName: '原始平台名称',
        contactPerson: '张三',
        contactPhone: '13800138000',
        status: 1
      });
      await platformRepository.save(platform);

      const updateData = {
        id: platform.id,
        platformName: '更新后的平台名称',
        contactPerson: '李四',
        contactPhone: '13900139000'
      };

      const response = await client.updatePlatform.$post({
        json: updateData
      }, {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

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

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

    it('应该验证平台名称重复（更新时）', async () => {
      // 创建两个平台
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const platformRepository = dataSource.getRepository(Platform);

      const platform1 = platformRepository.create({
        platformName: '平台A',
        contactPerson: '张三',
        contactPhone: '13800138000',
        status: 1
      });
      await platformRepository.save(platform1);

      const platform2 = platformRepository.create({
        platformName: '平台B',
        contactPerson: '李四',
        contactPhone: '13900139000',
        status: 1
      });
      await platformRepository.save(platform2);

      // 尝试将平台2的名称改为平台1的名称
      const updateData = {
        id: platform2.id,
        platformName: '平台A' // 重复的名称
      };

      const response = await client.updatePlatform.$post({
        json: updateData
      }, {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

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

    it('应该处理不存在的平台', async () => {
      const updateData = {
        id: 99999, // 不存在的ID
        platformName: '新名称'
      };

      const response = await client.updatePlatform.$post({
        json: updateData
      }, {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

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

  describe('GET /platform/getAllPlatforms', () => {
    it('应该成功获取平台列表（分页）', async () => {
      // 创建一些测试数据
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const platformRepository = dataSource.getRepository(Platform);

      for (let i = 1; i <= 5; i++) {
        const platform = platformRepository.create({
          platformName: `平台${i}`,
          contactPerson: `联系人${i}`,
          contactPhone: `1380013800${i}`,
          status: 1
        });
        await platformRepository.save(platform);
      }

      const response = await client.getAllPlatforms.$get({
        query: {
          skip: 0,
          take: 10
        }
      }, {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

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

      if (response.status === 200) {
        const data = await response.json();
        expect(data.data).toHaveLength(5);
        expect(data.total).toBe(5);
        expect(data.data[0].platformName).toBe('平台5'); // 按ID降序排列
      }
    });

    it('应该处理分页参数', async () => {
      // 创建更多测试数据
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const platformRepository = dataSource.getRepository(Platform);

      for (let i = 1; i <= 15; i++) {
        const platform = platformRepository.create({
          platformName: `分页平台${i}`,
          contactPerson: `联系人${i}`,
          contactPhone: `1380013800${i}`,
          status: 1
        });
        await platformRepository.save(platform);
      }

      const response = await client.getAllPlatforms.$get({
        query: {
          skip: 5,
          take: 5
        }
      }, {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

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

      if (response.status === 200) {
        const data = await response.json();
        expect(data.data).toHaveLength(5);
        expect(data.total).toBe(15);
      }
    });

    it('应该过滤已删除的平台（status=0）', async () => {
      // 创建测试数据：3个正常平台，2个已删除平台
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const platformRepository = dataSource.getRepository(Platform);

      // 创建3个正常平台
      for (let i = 1; i <= 3; i++) {
        const platform = platformRepository.create({
          platformName: `正常平台${i}`,
          contactPerson: `联系人${i}`,
          contactPhone: `1380013800${i}`,
          status: 1
        });
        await platformRepository.save(platform);
      }

      // 创建2个已删除平台
      for (let i = 4; i <= 5; i++) {
        const platform = platformRepository.create({
          platformName: `已删除平台${i}`,
          contactPerson: `联系人${i}`,
          contactPhone: `1380013800${i}`,
          status: 0
        });
        await platformRepository.save(platform);
      }

      const response = await client.getAllPlatforms.$get({
        query: {
          skip: 0,
          take: 10
        }
      }, {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

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

      if (response.status === 200) {
        const data = await response.json();
        // 应该只返回3个正常平台，不返回已删除的平台
        expect(data.data).toHaveLength(3);
        expect(data.total).toBe(3);

        // 验证返回的都是正常平台
        data.data.forEach((platform: any) => {
          expect(platform.status).toBe(1);
          expect(platform.platformName).toMatch(/^正常平台/);
        });
      }
    });
  });

  describe('GET /platform/searchPlatforms', () => {
    it('应该成功按名称搜索平台', async () => {
      // 创建测试数据
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const platformRepository = dataSource.getRepository(Platform);

      const platform1 = platformRepository.create({
        platformName: '微信平台',
        contactPerson: '张三',
        contactPhone: '13800138000',
        status: 1
      });
      await platformRepository.save(platform1);

      const platform2 = platformRepository.create({
        platformName: '支付宝平台',
        contactPerson: '李四',
        contactPhone: '13900139000',
        status: 1
      });
      await platformRepository.save(platform2);

      const response = await client.searchPlatforms.$get({
        query: {
          name: '微信',
          skip: 0,
          take: 10
        }
      }, {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

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

      if (response.status === 200) {
        const data = await response.json();
        expect(data.data).toHaveLength(1);
        expect(data.data[0].platformName).toBe('微信平台');
      }
    });

    it('应该验证搜索关键词不能为空', async () => {
      const response = await client.searchPlatforms.$get({
        query: {
          name: '', // 空关键词
          skip: 0,
          take: 10
        }
      }, {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

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

    it('应该过滤已删除的平台（搜索时）', async () => {
      // 创建测试数据
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const platformRepository = dataSource.getRepository(Platform);

      // 创建正常平台
      const normalPlatform = platformRepository.create({
        platformName: '测试搜索平台正常',
        contactPerson: '张三',
        contactPhone: '13800138000',
        status: 1
      });
      await platformRepository.save(normalPlatform);

      // 创建已删除的平台（不同名称）
      const deletedPlatform = platformRepository.create({
        platformName: '测试搜索平台已删除',
        contactPerson: '李四',
        contactPhone: '13900139000',
        status: 0
      });
      await platformRepository.save(deletedPlatform);

      const response = await client.searchPlatforms.$get({
        query: {
          name: '测试搜索',
          skip: 0,
          take: 10
        }
      }, {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

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

      if (response.status === 200) {
        const data = await response.json();
        // 应该只返回1个正常平台，不返回已删除的平台
        expect(data.data).toHaveLength(1);
        expect(data.total).toBe(1);
        expect(data.data[0].platformName).toBe('测试搜索平台正常');
        expect(data.data[0].status).toBe(1);
        expect(data.data[0].contactPerson).toBe('张三'); // 正常平台的联系人
      }
    });
  });

  describe('GET /platform/getPlatform/{id}', () => {
    it('应该成功获取单个平台详情', async () => {
      // 先创建一个平台
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const platformRepository = dataSource.getRepository(Platform);
      const platform = platformRepository.create({
        platformName: '测试平台详情',
        contactPerson: '张三',
        contactPhone: '13800138000',
        contactEmail: 'zhangsan@example.com',
        status: 1
      });
      await platformRepository.save(platform);

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

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

      if (response.status === 200) {
        const data = await response.json();
        expect(data?.platformName).toBe('测试平台详情');
        expect(data?.contactEmail).toBe('zhangsan@example.com');
      }
    });

    it('应该处理不存在的平台ID', async () => {
      const response = await client.getPlatform[':id'].$get({
        param: {
          id: 99999 // 不存在的ID
        }
      }, {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(200); // 返回200，但数据为null

      if (response.status === 200) {
        const data = await response.json();
        expect(data).toBeNull();
      }
    });
  });

  describe('认证测试', () => {
    it('应该验证所有端点需要认证', async () => {
      // 测试没有token的情况
      const response = await client.createPlatform.$post({
        json: {
          platformName: '测试平台'
        }
      });

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

    it('应该验证无效token', async () => {
      const response = await client.createPlatform.$post({
        json: {
          platformName: '测试平台'
        }
      }, {
        headers: {
          'Authorization': 'Bearer invalid_token'
        }
      });

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