import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import { testClient } from 'hono/testing';
import { IntegrationTestDatabase, setupIntegrationDatabaseHooksWithEntities } from '@d8d/shared-test-util';
import { JWTUtil } from '@d8d/shared-utils';
import { UserEntity, Role } from '@d8d/user-module';
import { File } from '@d8d/file-module';
import advertisementTypeRoutes from '../../src/routes/advertisement-types';
import { AdvertisementType } from '../../src/entities/advertisement-type.entity';

// 设置集成测试钩子
setupIntegrationDatabaseHooksWithEntities([UserEntity, File, Role, AdvertisementType])

describe('广告类型管理API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof advertisementTypeRoutes>>;
  let testToken: string;
  let testUser: UserEntity;

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

    // 获取数据源
    const dataSource = await IntegrationTestDatabase.getDataSource();

    // 创建测试用户
    const userRepository = dataSource.getRepository(UserEntity);
    testUser = userRepository.create({
      username: `test_user_${Date.now()}`,
      password: 'test_password',
      nickname: '测试用户',
      registrationSource: 'web'
    });
    await userRepository.save(testUser);

    // 生成测试用户的token
    testToken = JWTUtil.generateToken({
      id: testUser.id,
      username: testUser.username,
      roles: [{ name: 'user' }]
    });
  });

  describe('GET /advertisement-types', () => {
    it('应该返回广告类型列表', async () => {
      const response = await client.index.$get({
        query: {

        }
      },
      {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

      console.debug('广告类型列表响应状态:', response.status);
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const data = await response.json();
        expect(data).toHaveProperty('data');
        expect(Array.isArray(data.data)).toBe(true);
      }
    });

    it('应该拒绝未认证用户的访问', async () => {
      const response = await client.index.$get({
        query: {}
      });
      expect(response.status).toBe(401);
    });
  });

  describe('POST /advertisement-types', () => {
    it('应该成功创建广告类型', async () => {
      const createData = {
        name: '测试广告类型',
        code: 'test_type',
        remark: '测试备注',
        status: 1
      };

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

      console.debug('创建广告类型响应状态:', response.status);
      expect(response.status).toBe(201);

      if (response.status === 201) {
        const data = await response.json();
        expect(data).toHaveProperty('id');
        expect(data.name).toBe(createData.name);
        expect(data.code).toBe(createData.code);
        expect(data.status).toBe(createData.status);
      }
    });

    it('应该验证创建广告类型的必填字段', async () => {
      const invalidData = {
        // 缺少必填字段
        name: '',
        code: '',
        remark: '测试备注'
      };

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

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

    it('应该验证广告类型编码的唯一性', async () => {
      // 先创建一个广告类型
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const advertisementTypeRepository = dataSource.getRepository(AdvertisementType);
      const existingType = advertisementTypeRepository.create({
        name: '现有类型',
        code: 'existing_code',
        status: 1
      });
      await advertisementTypeRepository.save(existingType);

      // 尝试创建相同编码的类型
      const duplicateData = {
        name: '重复类型',
        code: 'existing_code', // 重复的编码
        status: 1
      };

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

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

  describe('GET /advertisement-types/:id', () => {
    it('应该返回指定广告类型的详情', async () => {
      // 先创建一个广告类型
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const advertisementTypeRepository = dataSource.getRepository(AdvertisementType);
      const testType = advertisementTypeRepository.create({
        name: '测试类型详情',
        code: 'test_type_detail',
        remark: '测试备注',
        status: 1
      });
      await advertisementTypeRepository.save(testType);

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

      console.debug('广告类型详情响应状态:', response.status);
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const data = await response.json();
        expect(data.id).toBe(testType.id);
        expect(data.name).toBe(testType.name);
        expect(data.code).toBe(testType.code);
      }
    });

    it('应该处理不存在的广告类型', async () => {
      const response = await client[':id'].$get({
        param: { id: 999999 }
      }, {
        headers: {
          'Authorization': `Bearer ${testToken}`
        }
      });

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

  describe('PUT /advertisement-types/:id', () => {
    it('应该成功更新广告类型', async () => {
      // 先创建一个广告类型
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const advertisementTypeRepository = dataSource.getRepository(AdvertisementType);
      const testType = advertisementTypeRepository.create({
        name: '原始类型',
        code: 'original_type',
        remark: '原始备注',
        status: 1
      });
      await advertisementTypeRepository.save(testType);

      const updateData = {
        name: '更新后的类型',
        code: 'updated_type',
        remark: '更新后的备注'
      };

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

      console.debug('更新广告类型响应状态:', response.status);
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const data = await response.json();
        expect(data.name).toBe(updateData.name);
        expect(data.code).toBe(updateData.code);
        expect(data.remark).toBe(updateData.remark);
      }
    });
  });

  describe('DELETE /advertisement-types/:id', () => {
    it('应该成功删除广告类型', async () => {
      // 先创建一个广告类型
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const advertisementTypeRepository = dataSource.getRepository(AdvertisementType);
      const testType = advertisementTypeRepository.create({
        name: '待删除类型',
        code: 'delete_type',
        remark: '待删除备注',
        status: 1
      });
      await advertisementTypeRepository.save(testType);

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

      console.debug('删除广告类型响应状态:', response.status);
      expect(response.status).toBe(204);

      // 验证广告类型确实被删除
      const deletedType = await advertisementTypeRepository.findOne({
        where: { id: testType.id }
      });
      expect(deletedType).toBeNull();
    });
  });
});