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 { adminActivitiesRoutesExport } from '@d8d/server/api';
import { AuthService } from '@d8d/server/modules/auth/auth.service';
import { ActivityType } from '@d8d/server/modules/activities/activity.entity';
import { UserService } from '@d8d/server/modules/users/user.service';

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

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

  beforeEach(async () => {
    // 创建测试客户端
    client = testClient(adminActivitiesRoutesExport).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();
      const testLocation = await TestDataFactory.createTestLocation(dataSource);

      const activityData = {
        name: '测试去程活动',
        description: '这是一个测试去程活动',
        type: ActivityType.DEPARTURE,
        startDate: '2025-10-17T08:00:00.000Z',
        endDate: '2025-10-17T18:00:00.000Z',
        venueLocationId: testLocation.id
      };

      const response = await client.activities.$post({
        json: activityData,
      },
      {
        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(activityData.name);
        expect(responseData.type).toBe(activityData.type);
        expect(responseData.isDisabled).toBe(0); // 默认启用

        // 断言数据库中存在活动
        await IntegrationTestAssertions.expectActivityToExist(responseData.id);
      }
    });

    it('应该成功创建返程活动', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const testLocation = await TestDataFactory.createTestLocation(dataSource);

      const activityData = {
        name: '测试返程活动',
        description: '这是一个测试返程活动',
        type: ActivityType.RETURN,
        startDate: '2025-10-17T16:00:00.000Z',
        endDate: '2025-10-17T20:00:00.000Z',
        venueLocationId: testLocation.id
      };

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

      expect(response.status).toBe(201);
      if (response.status === 201) {
        const responseData = await response.json();
        expect(responseData.type).toBe('return');
      }
    });

    it('应该拒绝创建无效活动类型的活动', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const testLocation = await TestDataFactory.createTestLocation(dataSource);

      const activityData = {
        name: '测试无效活动',
        description: '这是一个测试活动',
        type: 'invalid_type' as any, // 无效类型
        startDate: '2025-10-17T08:00:00.000Z',
        endDate: '2025-10-17T18:00:00.000Z',
        venueLocationId: testLocation.id
      };

      const response = await client.activities.$post({
        json: activityData,
      },
      {
        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.createTestActivity(dataSource, { name: '活动1', type: ActivityType.DEPARTURE });
      await TestDataFactory.createTestActivity(dataSource, { name: '活动2', type: ActivityType.RETURN });

      const response = await client.activities.$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 testActivity = await TestDataFactory.createTestActivity(dataSource, {
        name: '测试活动详情'
      });

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

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

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

      const updateData = {
        name: '更新后的活动名称',
        description: '更新后的活动描述'
      };

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

      // 验证数据库中的更新
      const getResponse = await client.activities[':id'].$get({
        param: { id: testActivity.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 testActivity = await TestDataFactory.createTestActivity(dataSource, {
        name: '测试状态切换',
        isDisabled: 0 // 启用状态
      });

      // 禁用活动
      const disableResponse = await client.activities[':id'].$put({
        param: { id: testActivity.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.activities[':id'].$put({
        param: { id: testActivity.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.activities[':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 testActivity = await TestDataFactory.createTestActivity(dataSource, {
        name: '测试活动删除'
      });

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

      IntegrationTestAssertions.expectStatus(response, 204);

      // 验证活动已从数据库中删除
      await IntegrationTestAssertions.expectActivityNotToExist(testActivity.id);

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

    it('应该返回404当删除不存在的活动时', async () => {
      const response = await client.activities[':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.createTestActivity(dataSource, { name: '搜索活动1', description: '测试描述1' });
      await TestDataFactory.createTestActivity(dataSource, { name: '搜索活动2', description: '测试描述2' });
      await TestDataFactory.createTestActivity(dataSource, { name: '其他活动', description: '其他描述' });

      const response = await client.activities.$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((activity) => activity.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.createTestActivity(dataSource, { name: '活动1', description: '测试描述搜索1' });
      await TestDataFactory.createTestActivity(dataSource, { name: '活动2', description: '测试描述搜索2' });

      const response = await client.activities.$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 descriptions = responseData.data.map((activity) => activity.description);
        expect(descriptions).toContain('测试描述搜索1');
        expect(descriptions).toContain('测试描述搜索2');
      }
    });

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

      await TestDataFactory.createTestActivity(dataSource, { name: '去程活动1', type: ActivityType.DEPARTURE });
      await TestDataFactory.createTestActivity(dataSource, { name: '去程活动2', type: ActivityType.DEPARTURE });
      await TestDataFactory.createTestActivity(dataSource, { name: '返程活动1', type: ActivityType.RETURN });

      const response = await client.activities.$get({
        query: { filters: JSON.stringify({ type: ActivityType.DEPARTURE }) }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

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

        const types = responseData.data.map((activity) => activity.type);
        expect(types.every((type: string) => type === 'departure')).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.createTestActivity(dataSource, {
          name: `性能测试活动_${i}`,
          description: `性能测试描述_${i}`
        });
      }

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

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