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

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

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

  beforeEach(async () => {
    // 创建测试客户端
    client = testClient(adminLocationsRoutesExport).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 testProvince = await TestDataFactory.createTestArea(dataSource, { level: 1 });
      const testCity = await TestDataFactory.createTestArea(dataSource, { level: 2, parentId: testProvince.id });
      const testDistrict = await TestDataFactory.createTestArea(dataSource, { level: 3, parentId: testCity.id });

      const locationData = {
        name: '测试地点',
        provinceId: testProvince.id,
        cityId: testCity.id,
        districtId: testDistrict.id,
        address: '测试详细地址',
        latitude: 39.9042,
        longitude: 116.4074
      };

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

        // 断言数据库中存在地点
        await IntegrationTestAssertions.expectLocationToExist(responseData.id);
      }
    });

    it('应该拒绝创建无效省市区的地点', async () => {
      const locationData = {
        name: '测试无效地点',
        provinceId: 999999,
        cityId: 999999,
        districtId: 999999,
        address: '测试详细地址',
        latitude: 39.9042,
        longitude: 116.4074
      };

      const response = await client.locations.$post({
        json: locationData,
      },
      {
        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.createTestLocation(dataSource, { name: '地点1' });
      await TestDataFactory.createTestLocation(dataSource, { name: '地点2' });

      const response = await client.locations.$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 testLocation = await TestDataFactory.createTestLocation(dataSource, {
        name: '测试地点详情'
      });

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

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

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

      const updateData = {
        name: '更新后的地点名称',
        address: '更新后的详细地址'
      };

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

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

      // 禁用地地点
      const disableResponse = await client.locations[':id'].$put({
        param: { id: testLocation.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.locations[':id'].$put({
        param: { id: testLocation.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.locations[':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 testLocation = await TestDataFactory.createTestLocation(dataSource, {
        name: '测试地点删除'
      });

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

      IntegrationTestAssertions.expectStatus(response, 204);

      // 验证地点已从数据库中删除
      await IntegrationTestAssertions.expectLocationNotToExist(testLocation.id);

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

    it('应该返回404当删除不存在的地点时', async () => {
      const response = await client.locations[':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.createTestLocation(dataSource, { name: '搜索地点1', address: '测试地址1' });
      await TestDataFactory.createTestLocation(dataSource, { name: '搜索地点2', address: '测试地址2' });
      await TestDataFactory.createTestLocation(dataSource, { name: '其他地点', address: '其他地址' });

      const response = await client.locations.$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((location) => location.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.createTestLocation(dataSource, { name: '地点1', address: '测试地址搜索1' });
      await TestDataFactory.createTestLocation(dataSource, { name: '地点2', address: '测试地址搜索2' });

      const response = await client.locations.$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 addresses = responseData.data.map((location) => location.address);
        expect(addresses).toContain('测试地址搜索1');
        expect(addresses).toContain('测试地址搜索2');
      }
    });

    it('应该能够按省市区筛选地点', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      const testProvince = await TestDataFactory.createTestArea(dataSource, { level: 1, name: '测试省份' });
      const testCity = await TestDataFactory.createTestArea(dataSource, { level: 2, name: '测试城市', parentId: testProvince.id });

      await TestDataFactory.createTestLocation(dataSource, {
        name: '地点1',
        provinceId: testProvince.id,
        cityId: testCity.id
      });
      await TestDataFactory.createTestLocation(dataSource, {
        name: '地点2',
        provinceId: testProvince.id,
        cityId: testCity.id
      });

      const response = await client.locations.$get({
        query: { filters: JSON.stringify({ provinceId: testProvince.id }) }
      },
      {
        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((location) => location.name);
        expect(names).toContain('地点1');
        expect(names).toContain('地点2');
      }
    });
  });

  describe('地点关联关系测试', () => {
    it('应该能够获取地点的完整省市区信息', async () => {
      const dataSource = await IntegrationTestDatabase.getDataSource();
      if (!dataSource) throw new Error('Database not initialized');

      const testLocation = await TestDataFactory.createTestLocation(dataSource, {
        name: '测试关联关系'
      });

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

      expect(response.status).toBe(200);
      if (response.status === 200) {
        const responseData = await response.json();
        expect(responseData).toHaveProperty('province');
        expect(responseData).toHaveProperty('city');
        expect(responseData).toHaveProperty('district');

        // 验证省市区信息存在
        expect(responseData.province).toBeDefined();
        expect(responseData.city).toBeDefined();
        expect(responseData.district).toBeDefined();
      }
    });
  });

  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.createTestLocation(dataSource, {
          name: `性能测试地点_${i}`,
          address: `性能测试地址_${i}`
        });
      }

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

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