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 { adminRoutesRoutesExport } from '@d8d/server/api';
import { AuthService } from '@d8d/server/modules/auth/auth.service';
import { UserService } from '@d8d/server/modules/users/user.service';
import { VehicleType } from '@d8d/server/modules/routes/route.schema';

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

describe('路线管理API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof adminRoutesRoutesExport>>['api']['v1']['admin'];
  let testToken: string;

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

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

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

    // 确保admin用户存在
    const user = await authService.ensureAdminExists();

    // 生成admin用户的token
    testToken = authService.generateToken(user);
  });

  describe('路线创建测试', () => {
    it('应该成功创建路线', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      // 先创建活动
      const testActivity = await TestDataFactory.createTestActivity(dataSource);
      // 创建起点和终点地点
      const startLocation = await TestDataFactory.createTestLocation(dataSource);
      const endLocation = await TestDataFactory.createTestLocation(dataSource);

      const routeData = {
        name: '测试路线',
        startLocationId: startLocation.id,
        endLocationId: endLocation.id,
        pickupPoint: '北京西站',
        dropoffPoint: '上海南站',
        departureTime: '2025-10-17T08:00:00.000Z',
        vehicleType: VehicleType.BUS,
        price: 200,
        seatCount: 40,
        availableSeats: 40,
        activityId: testActivity.id
      };

      const response = await client.routes.$post({
        json: routeData,
      },
      {
        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(routeData.name);
        expect(responseData.pickupPoint).toBe(routeData.pickupPoint);
        expect(responseData.dropoffPoint).toBe(routeData.dropoffPoint);
        expect(responseData.vehicleType).toBe(routeData.vehicleType);
        expect(responseData.price).toBe(routeData.price);
        expect(responseData.seatCount).toBe(routeData.seatCount);
        expect(responseData.availableSeats).toBe(routeData.availableSeats);
        expect(responseData.isDisabled).toBe(0); // 默认启用

        // 断言数据库中存在路线
        await IntegrationTestAssertions.expectRouteToExist(responseData.id);
      }
    });

    it('应该拒绝创建无效车型的路线', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      const testActivity = await TestDataFactory.createTestActivity(dataSource);

      const routeData = {
        name: '测试路线',
        startLocationId: 1,
        endLocationId: 2,
        pickupPoint: '北京西站',
        dropoffPoint: '上海南站',
        departureTime: '2025-10-17T08:00:00.000Z',
        vehicleType: 'invalid_vehicle' as any, // 无效车型，应该验证失败
        price: 200,
        seatCount: 40,
        availableSeats: 40,
        activityId: testActivity.id
      };

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

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

    it('应该拒绝创建价格为负数的路线', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      const testActivity = await TestDataFactory.createTestActivity(dataSource);

      const routeData = {
        name: '测试路线',
        startLocationId: 1,
        endLocationId: 2,
        pickupPoint: '北京西站',
        dropoffPoint: '上海南站',
        departureTime: '2025-10-17T08:00:00.000Z',
        vehicleType: VehicleType.BUS,
        price: -100, // 负数价格
        seatCount: 40,
        availableSeats: 40,
        activityId: testActivity.id
      };

      const response = await client.routes.$post({
        json: routeData,
      },
      {
        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.createTestRoute(dataSource, { name: '路线1', vehicleType: VehicleType.BUS });
      await TestDataFactory.createTestRoute(dataSource, { name: '路线2', vehicleType: VehicleType.MINIBUS });

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

      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 testRoute = await TestDataFactory.createTestRoute(dataSource, {
        name: '测试路线详情'
      });

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

      expect(response.status).toBe(200);
      if (response.status === 200) {
        const responseData = await response.json();
        expect(responseData.id).toBe(testRoute.id);
        expect(responseData.name).toBe(testRoute.name);
        expect(responseData.vehicleType).toBe(testRoute.vehicleType);
      }
    });

    it('应该返回404当路线不存在时', async () => {
      const response = await client.routes[':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 testRoute = await TestDataFactory.createTestRoute(dataSource, {
        name: '测试路线更新'
      });

      const updateData = {
        name: '更新后的路线名称',
        startLocationId: 3,
        price: 300
      };

      const response = await client.routes[':id'].$put({
        param: { id: testRoute.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.startLocationId).toBe(updateData.startLocationId);
        expect(parseFloat(responseData.price as unknown as string)).toBe(updateData.price);
      }

      // 验证数据库中的更新
      const getResponse = await client.routes[':id'].$get({
        param: { id: testRoute.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);
      }
    });

    it('应该成功启用/禁用路线', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      const testRoute = await TestDataFactory.createTestRoute(dataSource, {
        name: '测试状态切换',
        isDisabled: 0 // 启用状态
      });

      // 禁用路线
      const disableResponse = await client.routes[':id'].$put({
        param: { id: testRoute.id },
        json: { isDisabled: 1 } // 禁用
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      expect(disableResponse.status).toBe(200);
      if (disableResponse.status === 200) {
        const disableData = await disableResponse.json();
        expect(disableData.isDisabled).toBe(1);
      }

      // 重新启用路线
      const enableResponse = await client.routes[':id'].$put({
        param: { id: testRoute.id },
        json: { isDisabled: 0 } // 启用
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      expect(enableResponse.status).toBe(200);
      if (enableResponse.status === 200) {
        const enableData = await enableResponse.json();
        expect(enableData.isDisabled).toBe(0);
      }
    });

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

      const response = await client.routes[':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 testRoute = await TestDataFactory.createTestRoute(dataSource, {
        name: '测试路线删除'
      });

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

      IntegrationTestAssertions.expectStatus(response, 204);

      // 验证路线已从数据库中删除
      await IntegrationTestAssertions.expectRouteNotToExist(testRoute.id);

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

    it('应该返回404当删除不存在的路线时', async () => {
      const response = await client.routes[':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.createTestRoute(dataSource, { name: '搜索路线1' });
      await TestDataFactory.createTestRoute(dataSource, { name: '搜索路线2' });
      await TestDataFactory.createTestRoute(dataSource, { name: '其他路线' });

      const response = await client.routes.$get({
        query: { keyword: '搜索路线' }
      },
      {
        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((route) => route.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.createTestRoute(dataSource, { name: '路线1' });
      await TestDataFactory.createTestRoute(dataSource, { name: '路线2' });

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

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

        const names = responseData.data.map((route) => route.name);
        expect(names).toContain('路线1');
        expect(names).toContain('路线2');
      }
    });

    it('应该能够按车型筛选路线', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      await TestDataFactory.createTestRoute(dataSource, { name: '大巴路线1', vehicleType: VehicleType.BUS });
      await TestDataFactory.createTestRoute(dataSource, { name: '大巴路线2', vehicleType: VehicleType.BUS });
      await TestDataFactory.createTestRoute(dataSource, { name: '中巴路线', vehicleType: VehicleType.MINIBUS });

      const response = await client.routes.$get({
        query: { filters: JSON.stringify({ vehicleType: 'bus' }) }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

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

        const vehicleTypes = responseData.data.map((route) => route.vehicleType);
        expect(vehicleTypes.every((type: string) => type === 'bus')).toBe(true);
      }
    });
  });

  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.createTestRoute(dataSource, {
          name: `性能测试路线_${i}`
        });
      }

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

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