import { describe, it, expect, beforeEach } from 'vitest';
import { testClient } from 'hono/testing';
import {
  IntegrationTestDatabase,
  setupIntegrationDatabaseHooksWithEntities
} from '@d8d/shared-test-util';
import {
  IntegrationTestAssertions
} from '../utils/integration-test-utils';
import { userRoutesMt } from '../../src/routes/index.mt';
import { UserEntityMt } from '../../src/entities/user.entity.mt';
import { RoleMt } from '../../src/entities/role.entity.mt';
import { TestDataFactory } from '../utils/integration-test-db';
import { AuthService } from '@d8d/core-module-mt/auth-module-mt';
import { UserServiceMt } from '../../src/services/user.service.mt';
import { FileMt } from '@d8d/core-module-mt/file-module-mt';

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

describe('用户路由API集成测试 (使用hono/testing)', () => {
  let client: ReturnType<typeof testClient<typeof userRoutesMt>>;
  let authService: AuthService;
  let userService: UserServiceMt;
  let testToken: string;
  let testUser: any;

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

    // 获取数据源
    const dataSource = await IntegrationTestDatabase.getDataSource();
    if (!dataSource) throw new Error('Database not initialized');

    // 初始化服务
    userService = new UserServiceMt(dataSource);
    authService = new AuthService(userService);

    // 创建测试用户并生成token
    testUser = await TestDataFactory.createTestUser(dataSource, {
      username: 'testuser_auth',
      password: 'TestPassword123!',
      email: 'testuser_auth@example.com'
    });

    // 生成测试用户的token
    testToken = authService.generateToken(testUser);
  });

  describe('用户创建路由测试', () => {
    it('应该拒绝无认证令牌的用户创建请求', async () => {
      const userData = {
        username: 'testuser_create_route_no_auth',
        email: 'testcreate_route_no_auth@example.com',
        password: 'TestPassword123!',
        nickname: 'Test User Route No Auth',
        phone: '13800138001'
      };

      const response = await client.index.$post({
        json: userData
      });

      // 应该返回401状态码，因为缺少认证
      expect(response.status).toBe(401);
      if (response.status === 401) {
        const responseData = await response.json();
        expect(responseData.message).toContain('Authorization header missing');
      }
    });

    it('应该拒绝无效认证令牌的用户创建请求', async () => {
      const userData = {
        username: 'testuser_create_route_invalid_token',
        email: 'testcreate_route_invalid_token@example.com',
        password: 'TestPassword123!',
        nickname: 'Test User Route Invalid Token',
        phone: '13800138001'
      };

      const response = await client.index.$post({
        json: userData
      }, {
        headers: {
          'Authorization': 'Bearer invalid.token.here'
        }
      });

      // 应该返回401状态码，因为令牌无效
      expect(response.status).toBe(401);
      if (response.status === 401) {
        const responseData = await response.json();
        expect(responseData.message).toContain('Invalid token');
      }
    });

    it('应该成功创建用户（使用有效认证令牌）', async () => {
      const userData = {
        username: 'testuser_create_route',
        email: 'testcreate_route@example.com',
        password: 'TestPassword123!',
        nickname: 'Test User Route',
        phone: '13800138001'
      };

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

      // 断言响应
      expect(response.status).toBe(201);
      if (response.status === 201) {
        const responseData = await response.json();
        expect(responseData).toHaveProperty('id');
        expect(responseData.username).toBe(userData.username);
        expect(responseData.email).toBe(userData.email);
        expect(responseData.nickname).toBe(userData.nickname);

        // 断言数据库中存在用户
        await IntegrationTestAssertions.expectUserToExist(userData.username);
      }
    });

    it('应该拒绝创建重复用户名的用户', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      // 先创建一个用户（同租户）
      await TestDataFactory.createTestUser(dataSource, {
        username: 'duplicate_user_route',
        tenantId: testUser.tenantId // 使用测试用户的租户ID
      });

      // 尝试创建相同用户名的用户（同租户）
      const userData = {
        username: 'duplicate_user_route',
        email: 'different_route@example.com',
        password: 'TestPassword123!',
        nickname: 'Test User'
      };

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

      // 应该返回错误（同租户内用户名重复）
      expect(response.status).toBe(400);
      if (response.status === 400) {
        const responseData = await response.json();
        expect(responseData.message).toContain('用户名已存在');
      }
    });

    it('应该拒绝创建无效邮箱的用户', async () => {
      const userData = {
        username: 'testuser_invalid_email_route',
        email: 'invalid-email',
        password: 'TestPassword123!',
        nickname: 'Test User'
      };

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

      // 应该返回验证错误或服务器错误
      expect([400, 500]).toContain(response.status);

      // 只要返回了错误状态码就认为测试通过
      // 不检查具体的响应格式，因为可能因实现而异
    });
  });

  describe('用户读取路由测试', () => {
    it('应该成功获取用户列表', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      // 创建几个测试用户
      await TestDataFactory.createTestUser(dataSource, { username: 'user1_route' });
      await TestDataFactory.createTestUser(dataSource, { username: 'user2_route' });

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

      if (response.status !== 200) {
        const errorData = await response.json();
        console.debug('获取用户列表失败:', errorData);
      }
      expect(response.status).toBe(200);
      if (response.status === 200) {
        const responseData = await response.json();
        expect(Array.isArray(responseData.data)).toBe(true);
        expect(responseData.data.length).toBeGreaterThanOrEqual(2);
      }
    });

    it('应该成功获取单个用户详情', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      const testUser = await TestDataFactory.createTestUser(dataSource, {
        username: 'testuser_detail_route'
      });

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

      expect(response.status).toBe(200);
      if (response.status === 200) {
        const responseData = await response.json();
        expect(responseData.id).toBe(testUser.id);
        expect(responseData.username).toBe(testUser.username);
        expect(responseData.email).toBe(testUser.email);
      }
    });

    it('应该返回404当用户不存在时', async () => {
      const response = await client[':id'].$get({
        param: { id: 999999 }
      }, {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(404);
      if (response.status === 404) {
        const responseData = await response.json();
        expect(responseData.message).toContain('资源不存在');
      }
    });
  });

  describe('用户更新路由测试', () => {
    it('应该拒绝无认证令牌的用户更新请求', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      const testUser = await TestDataFactory.createTestUser(dataSource, {
        username: 'testuser_update_no_auth'
      });

      const updateData = {
        nickname: 'Updated Name Route',
        email: 'updated_route@example.com'
      };

      const response = await client[':id'].$put({
        param: { id: testUser.id },
        json: updateData
      });

      // 应该返回401状态码，因为缺少认证
      expect(response.status).toBe(401);
      if (response.status === 401) {
        const responseData = await response.json();
        expect(responseData.message).toContain('Authorization header missing');
      }
    });

    it('应该成功更新用户信息（使用有效认证令牌）', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      const testUser = await TestDataFactory.createTestUser(dataSource, {
        username: 'testuser_update_route'
      });

      const updateData = {
        nickname: 'Updated Name Route',
        email: 'updated_route@example.com'
      };

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

      expect(response.status).toBe(200);
      if (response.status === 200) {
        const responseData = await response.json();
        expect(responseData.nickname).toBe(updateData.nickname);
        expect(responseData.email).toBe(updateData.email);
      }

      // 验证数据库中的更新
      const getResponse = await client[':id'].$get({
        param: { id: testUser.id }
      });
      if (getResponse.status === 200) {
        expect(getResponse.status).toBe(200);
        const getResponseData = await getResponse.json();
        expect(getResponseData.nickname).toBe(updateData.nickname);
      }
    });

    it('应该返回404当更新不存在的用户时', async () => {
      const updateData = {
        nickname: 'Updated Name',
        email: 'updated@example.com'
      };

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

      expect(response.status).toBe(404);
      if (response.status === 404) {
        const responseData = await response.json();
        expect(responseData.message).toContain('资源不存在');
      }
    });
  });

  describe('用户删除路由测试', () => {
    it('应该拒绝无认证令牌的用户删除请求', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      const testUser = await TestDataFactory.createTestUser(dataSource, {
        username: 'testuser_delete_no_auth'
      });

      const response = await client[':id'].$delete({
        param: { id: testUser.id }
      });

      // 应该返回401状态码，因为缺少认证
      expect(response.status).toBe(401);
      if (response.status === 401) {
        const responseData = await response.json();
        expect(responseData.message).toContain('Authorization header missing');
      }
    });

    it('应该成功删除用户（使用有效认证令牌）', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      const testUser = await TestDataFactory.createTestUser(dataSource, {
        username: 'testuser_delete_route'
      });

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

      IntegrationTestAssertions.expectStatus(response, 204);

      // 验证用户已从数据库中删除
      await IntegrationTestAssertions.expectUserNotToExist('testuser_delete_route');

      // 验证再次获取用户返回404
      const getResponse = await client[':id'].$get({
        param: { id: testUser.id }
      }, {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });
      IntegrationTestAssertions.expectStatus(getResponse, 404);
    });

    it('应该返回404当删除不存在的用户时', async () => {
      const response = await client[':id'].$delete({
        param: { id: 999999 }
      }, {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      IntegrationTestAssertions.expectStatus(response, 404);
      if (response.status === 404) {
        const responseData = await response.json();
        expect(responseData.message).toContain('资源不存在');
      }
    });
  });

  describe('用户搜索路由测试', () => {
    it('应该能够按用户名搜索用户', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      await TestDataFactory.createTestUser(dataSource, { username: 'search_user_1_route', email: 'search1_route@example.com' });
      await TestDataFactory.createTestUser(dataSource, { username: 'search_user_2_route', email: 'search2_route@example.com' });
      await TestDataFactory.createTestUser(dataSource, { username: 'other_user_route', email: 'other_route@example.com' });

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

      IntegrationTestAssertions.expectStatus(response, 200);
      if (response.status === 200) {
        const responseData = await response.json();
        expect(Array.isArray(responseData.data)).toBe(true);
        expect(responseData.data.length).toBe(2);

        // 验证搜索结果包含正确的用户
        const usernames = responseData.data.map((user: any) => user.username);
        expect(usernames).toContain('search_user_1_route');
        expect(usernames).toContain('search_user_2_route');
        expect(usernames).not.toContain('other_user_route');
      }
    });

    it('应该能够按邮箱搜索用户', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      await TestDataFactory.createTestUser(dataSource, { username: 'user_email_1_route', email: 'test.email1_route@example.com' });
      await TestDataFactory.createTestUser(dataSource, { username: 'user_email_2_route', email: 'test.email2_route@example.com' });

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

      IntegrationTestAssertions.expectStatus(response, 200);
      if (response.status === 200) {
        const responseData = await response.json();
        expect(responseData.data.length).toBe(2);

        const emails = responseData.data.map((user: any) => user.email);
        expect(emails).toContain('test.email1_route@example.com');
        expect(emails).toContain('test.email2_route@example.com');
      }
    });
  });

  describe('性能测试', () => {
    it('用户列表查询响应时间应小于200ms', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      // 创建一些测试数据
      for (let i = 0; i < 10; i++) {
        await TestDataFactory.createTestUser(dataSource, {
          username: `perf_user_${i}_route`,
          email: `perf${i}_route@example.com`
        });
      }

      const startTime = Date.now();
      const response = await client.index.$get({
        query: {}
      }, {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });
      const endTime = Date.now();
      const responseTime = endTime - startTime;

      IntegrationTestAssertions.expectStatus(response, 200);
      expect(responseTime).toBeLessThan(200); // 响应时间应小于200ms
    });
  });

  describe('认证令牌测试', () => {
    it('应该能够生成有效的JWT令牌', async () => {
      // 验证生成的令牌是有效的字符串
      expect(typeof testToken).toBe('string');
      expect(testToken.length).toBeGreaterThan(0);

      // 验证令牌可以被正确解码
      const decoded = authService.verifyToken(testToken);
      expect(decoded).toHaveProperty('id');
      expect(decoded).toHaveProperty('username');
      expect(decoded.id).toBe(testUser.id);
      expect(decoded.username).toBe(testUser.username);
    });

    it('应该拒绝过期令牌的请求', async () => {
      // 创建立即过期的令牌
      const expiredToken = authService.generateToken(testUser, '1ms');

      // 等待令牌过期
      await new Promise(resolve => setTimeout(resolve, 10));

      const response = await client.index.$post({
        json: {
          username: 'test_expired_token',
          email: 'test_expired@example.com',
          password: 'TestPassword123!',
          nickname: 'Test Expired Token'
        }
      }, {
        headers: {
          'Authorization': `Bearer ${expiredToken}`
        }
      });

      // 应该返回401状态码，因为令牌过期
      expect(response.status).toBe(401);
      if (response.status === 401) {
        const responseData = await response.json();
        expect(responseData.message).toContain('Invalid token');
      }
    });

    it('应该拒绝格式错误的认证头', async () => {
      const response = await client.index.$post({
        json: {
          username: 'test_bad_auth_header',
          email: 'test_bad_auth@example.com',
          password: 'TestPassword123!',
          nickname: 'Test Bad Auth Header'
        }
      }, {
        headers: {
          'Authorization': 'Basic invalid_format'
        }
      });

      // 应该返回401状态码，因为认证头格式错误
      expect(response.status).toBe(401);
      if (response.status === 401) {
        const responseData = await response.json();
        expect(responseData.message).toContain('Authorization header missing');
      }
    });
  });

  describe('租户隔离测试', () => {
    let tenant1Token: string;
    let tenant2Token: string;
    let tenant1User: any;
    let tenant2User: any;

    beforeEach(async () => {
      // 创建租户1的用户和token
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      tenant1User = await TestDataFactory.createTestUser(dataSource, {
        username: 'tenant1_user',
        password: 'password123',
        email: 'tenant1@example.com',
        tenantId: 1
      });

      tenant2User = await TestDataFactory.createTestUser(dataSource, {
        username: 'tenant2_user',
        password: 'password123',
        email: 'tenant2@example.com',
        tenantId: 2
      });

      // 生成不同租户的token，确保包含完整的用户信息
      tenant1Token = authService.generateToken(tenant1User);
      tenant2Token = authService.generateToken(tenant2User);
    });

    it('应该只返回当前租户的用户列表', async () => {
      // 租户1只能看到租户1的用户
      const response1 = await client.index.$get({
        query: {}
      }, {
        headers: {
          'Authorization': `Bearer ${tenant1Token}`
        }
      });

      console.debug('租户1列表响应状态:', response1.status);
      if (response1.status !== 200) {
        const errorResult = await response1.json();
        console.debug('租户1列表错误响应:', errorResult);
      }
      expect(response1.status).toBe(200);
      const result1 = await response1.json();
      console.debug('租户1返回的用户数据:', (result1 as any).data);
      expect((result1 as any).data).toHaveLength(2);
      expect((result1 as any).data.every((user: any) => user.tenantId === 1)).toBe(true);

      // 租户2只能看到租户2的用户
      const response2 = await client.index.$get({
        query: {}
      }, {
        headers: {
          'Authorization': `Bearer ${tenant2Token}`
        }
      });

      console.debug('租户2列表响应状态:', response2.status);
      if (response2.status !== 200) {
        const errorResult = await response2.json();
        console.debug('租户2列表错误响应:', errorResult);
      }
      expect(response2.status).toBe(200);
      const result2 = await response2.json();
      console.debug('租户2返回的用户数据:', (result2 as any).data);
      expect((result2 as any).data).toHaveLength(1);
      expect((result2 as any).data.every((user: any) => user.tenantId === 2)).toBe(true);
    });

    it('应该拒绝跨租户访问用户详情', async () => {
      // 租户1尝试访问租户2的用户
      const response = await client[':id'].$get({
        param: { id: tenant2User.id }
      }, {
        headers: {
          'Authorization': `Bearer ${tenant1Token}`
        }
      });

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

    it('应该拒绝跨租户更新用户', async () => {
      const updateData = {
        nickname: '尝试跨租户更新'
      };

      // 租户1尝试更新租户2的用户
      const response = await client[':id'].$put({
        param: { id: tenant2User.id },
        json: updateData
      }, {
        headers: {
          'Authorization': `Bearer ${tenant1Token}`
        }
      });

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

    it('应该拒绝跨租户删除用户', async () => {
      // 租户1尝试删除租户2的用户
      const response = await client[':id'].$delete({
        param: { id: tenant2User.id }
      }, {
        headers: {
          'Authorization': `Bearer ${tenant1Token}`
        }
      });

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