import { describe, it, expect, beforeEach } from 'vitest';
import { testClient } from 'hono/testing';
import {
  IntegrationTestDatabase,
  setupIntegrationDatabaseHooks,
  TestDataFactory
} from '~/utils/server/integration-test-db';
import { IntegrationTestAssertions } from '~/utils/server/integration-test-utils';
import { passengersRoutesExport } from '@d8d/server/api';
import { AuthService } from '@d8d/server/modules/auth/auth.service';
import { UserService } from '@d8d/server/modules/users/user.service';
import { IdType } from '@d8d/server/modules/passengers/passenger.schema';

// 设置集成测试钩子
setupIntegrationDatabaseHooks()

describe('用户端乘客API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof passengersRoutesExport>>['api']['v1'];
  let testToken: string;
  let testUser: any;

  beforeEach(async () => {
    // 创建测试客户端
    client = testClient(passengersRoutesExport).api.v1;

    // 创建测试用户并生成token
    const dataSource = await IntegrationTestDatabase.getDataSource();

    const userService = new UserService(dataSource);
    const authService = new AuthService(userService);

    // 创建测试用户
    testUser = await TestDataFactory.createTestUser(dataSource);

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

  describe('乘客创建测试', () => {
    it('应该成功创建乘客', async () => {
      const passengerData = {
        name: '测试乘客',
        idType: IdType.ID_CARD,
        idNumber: '110101199001011234',
        phone: '13812345678',
        isDefault: false
      };

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

      // 断言响应
      expect(response.status).toBe(201);
      if (response.status === 201) {
        const responseData = await response.json();
        expect(responseData).toHaveProperty('id');
        expect(responseData.name).toBe(passengerData.name);
        expect(responseData.idType).toBe(passengerData.idType);
        expect(responseData.idNumber).toBe(passengerData.idNumber);
        expect(responseData.phone).toBe(passengerData.phone);
        expect(responseData.isDefault).toBe(passengerData.isDefault);
        expect(responseData.userId).toBe(testUser.id);

        // 断言数据库中存在乘客
        await IntegrationTestAssertions.expectPassengerToExist(responseData.id);
      }
    });

    it('应该成功创建默认乘客', async () => {
      const passengerData = {
        name: '默认乘客',
        idType: IdType.PASSPORT,
        idNumber: 'E12345678',
        phone: '13987654321',
        isDefault: true
      };

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

      expect(response.status).toBe(201);
      if (response.status === 201) {
        const responseData = await response.json();
        expect(responseData.isDefault).toBe(true);
      }
    });

    it('应该拒绝创建无效证件类型的乘客', async () => {
      const passengerData = {
        name: '测试乘客',
        idType: 'invalid_type' as any, // 无效类型
        idNumber: '110101199001011234',
        phone: '13812345678',
        isDefault: false
      };

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

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

    it('应该拒绝创建缺少必填字段的乘客', async () => {
      const passengerData = {
        name: '', // 空字符串作为无效值
        idType: IdType.ID_CARD,
        idNumber: '110101199001011234',
        phone: '13812345678',
        isDefault: false
      };

      const response = await client.passengers.$post({
        json: passengerData,
      },
      {
        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.createTestPassenger(dataSource, {
        userId: testUser.id,
        name: '乘客1'
      });
      await TestDataFactory.createTestPassenger(dataSource, {
        userId: testUser.id,
        name: '乘客2'
      });

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

      if (response.status !== 200) {
        const errorData = await response.json() as any;
        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).toBe(2);

        // 验证返回的乘客都属于当前用户
        responseData.data.forEach((passenger: any) => {
          expect(passenger.userId).toBe(testUser.id);
        });
      }
    });

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

      const testPassenger = await TestDataFactory.createTestPassenger(dataSource, {
        userId: testUser.id,
        name: '测试乘客详情'
      });

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

      expect(response.status).toBe(200);
      if (response.status === 200) {
        const responseData = await response.json();
        expect(responseData.id).toBe(testPassenger.id);
        expect(responseData.name).toBe(testPassenger.name);
        expect(responseData.idType).toBe(testPassenger.idType);
        expect(responseData.idNumber).toBe(testPassenger.idNumber);
        expect(responseData.phone).toBe(testPassenger.phone);
        expect(responseData.userId).toBe(testUser.id);
      }
    });

    it('应该返回404当乘客不存在时', async () => {
      const response = await client.passengers[':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('乘客不存在');
      }
    });

    it('应该拒绝访问其他用户的乘客', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      // 创建另一个用户
      const otherUser = await TestDataFactory.createTestUser(dataSource);

      // 为其他用户创建乘客
      const otherPassenger = await TestDataFactory.createTestPassenger(dataSource, {
        userId: otherUser.id,
        name: '其他用户的乘客'
      });

      // 当前用户尝试访问其他用户的乘客
      const response = await client.passengers[':id'].$get({
        param: { id: otherPassenger.id }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      // 应该返回403权限错误
      expect(response.status).toBe(403);
      if (response.status === 403) {
        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 testPassenger = await TestDataFactory.createTestPassenger(dataSource, {
        userId: testUser.id,
        name: '测试乘客更新'
      });

      const updateData = {
        name: '更新后的乘客名称',
        phone: '13987654321',
        isDefault: true
      };

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

      expect(response.status).toBe(200);
      if (response.status === 200) {
        const responseData = await response.json();
        expect(responseData.name).toBe(updateData.name);
        expect(responseData.phone).toBe(updateData.phone);
        expect(responseData.isDefault).toBe(updateData.isDefault);
      }

      // 验证数据库中的更新
      const getResponse = await client.passengers[':id'].$get({
        param: { id: testPassenger.id }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });
      if (getResponse.status === 200) {
        expect(getResponse.status).toBe(200);
        const getResponseData = await getResponse.json();
        expect(getResponseData.name).toBe(updateData.name);
        expect(getResponseData.phone).toBe(updateData.phone);
      }
    });

    it('应该返回404当更新不存在的乘客时', async () => {
      const updateData = {
        name: '更新后的名称'
      };

      const response = await client.passengers[':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('乘客不存在');
      }
    });

    it('应该拒绝更新其他用户的乘客', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      // 创建另一个用户
      const otherUser = await TestDataFactory.createTestUser(dataSource);

      // 为其他用户创建乘客
      const otherPassenger = await TestDataFactory.createTestPassenger(dataSource, {
        userId: otherUser.id,
        name: '其他用户的乘客'
      });

      const updateData = {
        name: '尝试修改的名称'
      };

      // 当前用户尝试更新其他用户的乘客
      const response = await client.passengers[':id'].$put({
        param: { id: otherPassenger.id },
        json: updateData
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      // 应该返回403权限错误
      expect(response.status).toBe(403);
      if (response.status === 403) {
        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 testPassenger = await TestDataFactory.createTestPassenger(dataSource, {
        userId: testUser.id,
        name: '测试乘客删除'
      });

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

      IntegrationTestAssertions.expectStatus(response, 204);

      // 验证乘客已从数据库中删除
      await IntegrationTestAssertions.expectPassengerNotToExist(testPassenger.id);

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

    it('应该返回404当删除不存在的乘客时', async () => {
      const response = await client.passengers[':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('乘客不存在');
      }
    });

    it('应该拒绝删除其他用户的乘客', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      // 创建另一个用户
      const otherUser = await TestDataFactory.createTestUser(dataSource);

      // 为其他用户创建乘客
      const otherPassenger = await TestDataFactory.createTestPassenger(dataSource, {
        userId: otherUser.id,
        name: '其他用户的乘客'
      });

      // 当前用户尝试删除其他用户的乘客
      const response = await client.passengers[':id'].$delete({
        param: { id: otherPassenger.id }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      // 应该返回403权限错误
      expect(response.status).toBe(403);
      if (response.status === 403) {
        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 testPassenger = await TestDataFactory.createTestPassenger(dataSource, {
        userId: testUser.id,
        name: '测试设置默认乘客',
        isDefault: false
      });

      const response = await client.passengers[':id']['set-default'].$post({
        param: { id: testPassenger.id }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      expect(response.status).toBe(200);
      if (response.status === 200) {
        const responseData = await response.json();
        expect(responseData.isDefault).toBe(true);
      }

      // 验证数据库中乘客已设置为默认
      const getResponse = await client.passengers[':id'].$get({
        param: { id: testPassenger.id }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });
      if (getResponse.status === 200) {
        const getResponseData = await getResponse.json();
        expect(getResponseData.isDefault).toBe(true);
      }
    });

    it('应该返回404当设置不存在的乘客为默认时', async () => {
      const response = await client.passengers[':id']['set-default'].$post({
        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('乘客不存在');
      }
    });

    it('应该拒绝设置其他用户的乘客为默认', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      // 创建另一个用户
      const otherUser = await TestDataFactory.createTestUser(dataSource);

      // 为其他用户创建乘客
      const otherPassenger = await TestDataFactory.createTestPassenger(dataSource, {
        userId: otherUser.id,
        name: '其他用户的乘客'
      });

      // 当前用户尝试设置其他用户的乘客为默认
      const response = await client.passengers[':id']['set-default'].$post({
        param: { id: otherPassenger.id }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      // 应该返回403权限错误
      expect(response.status).toBe(403);
      if (response.status === 403) {
        const responseData = await response.json();
        expect(responseData.message).toContain('无权设置');
      }
    });

    it('设置默认乘客时应该取消其他乘客的默认状态', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      // 创建两个乘客，其中一个为默认
      const defaultPassenger = await TestDataFactory.createTestPassenger(dataSource, {
        userId: testUser.id,
        name: '原默认乘客',
        isDefault: true
      });
      const newDefaultPassenger = await TestDataFactory.createTestPassenger(dataSource, {
        userId: testUser.id,
        name: '新默认乘客',
        isDefault: false
      });

      // 设置新的默认乘客
      const response = await client.passengers[':id']['set-default'].$post({
        param: { id: newDefaultPassenger.id }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

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

      // 验证新乘客为默认
      const getNewResponse = await client.passengers[':id'].$get({
        param: { id: newDefaultPassenger.id }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });
      if (getNewResponse.status === 200) {
        const newPassengerData = await getNewResponse.json();
        expect(newPassengerData.isDefault).toBe(true);
      }

      // 验证原默认乘客不再是默认
      const getOldResponse = await client.passengers[':id'].$get({
        param: { id: defaultPassenger.id }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });
      if (getOldResponse.status === 200) {
        const oldPassengerData = await getOldResponse.json();
        expect(oldPassengerData.isDefault).toBe(false);
      }
    });
  });

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

      await TestDataFactory.createTestPassenger(dataSource, {
        userId: testUser.id,
        name: '搜索乘客1',
        phone: '13811111111'
      });
      await TestDataFactory.createTestPassenger(dataSource, {
        userId: testUser.id,
        name: '搜索乘客2',
        phone: '13822222222'
      });
      await TestDataFactory.createTestPassenger(dataSource, {
        userId: testUser.id,
        name: '其他乘客',
        phone: '13833333333'
      });

      const response = await client.passengers.$get({
        query: { keyword: '搜索乘客', page: 1, pageSize: 10 }
      },
      {
        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 names = responseData.data.map((passenger: any) => passenger.name);
        expect(names).toContain('搜索乘客1');
        expect(names).toContain('搜索乘客2');
        expect(names).not.toContain('其他乘客');
      }
    });

    it('应该能够按手机号搜索乘客', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      await TestDataFactory.createTestPassenger(dataSource, {
        userId: testUser.id,
        name: '乘客1',
        phone: '13811112222'
      });
      await TestDataFactory.createTestPassenger(dataSource, {
        userId: testUser.id,
        name: '乘客2',
        phone: '13811113333'
      });

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

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

        const phones = responseData.data.map((passenger: any) => passenger.phone);
        expect(phones).toContain('13811112222');
        expect(phones).toContain('13811113333');
      }
    });

    it('应该能够按证件号码搜索乘客', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      await TestDataFactory.createTestPassenger(dataSource, {
        userId: testUser.id,
        name: '乘客1',
        idNumber: '110101199001011111'
      });
      await TestDataFactory.createTestPassenger(dataSource, {
        userId: testUser.id,
        name: '乘客2',
        idNumber: '110101199001012222'
      });

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

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

        const idNumbers = responseData.data.map((passenger: any) => passenger.idNumber);
        expect(idNumbers).toContain('110101199001011111');
        expect(idNumbers).toContain('110101199001012222');
      }
    });
  });

  describe('权限控制测试', () => {
    it('应该拒绝未认证用户的访问', async () => {
      const response = await client.passengers.$get({
        query: { page: 1, pageSize: 10 }
      });

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

    it('应该拒绝无效token的访问', async () => {
      const response = await client.passengers.$get({
        query: { page: 1, pageSize: 10 }
      },
      {
        headers: {
          'Authorization': 'Bearer invalid_token'
        }
      });

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

  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.createTestPassenger(dataSource, {
          userId: testUser.id,
          name: `性能测试乘客_${i}`,
          phone: `138${i.toString().padStart(8, '0')}`
        });
      }

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

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