
import { IntegrationTestDatabase } from './integration-test-db';
import { UserEntity } from '@/server/modules/users/user.entity';



/**
 * 集成测试断言工具
 */
export class IntegrationTestAssertions {
  /**
   * 断言响应状态码
   */
  static expectStatus(response: { status: number }, expectedStatus: number): void {
    if (response.status !== expectedStatus) {
      throw new Error(`Expected status ${expectedStatus}, but got ${response.status}`);
    }
  }

  /**
   * 断言响应包含特定字段
   */
  static expectResponseToHave(response: { data: any }, expectedFields: Record<string, any>): void {
    for (const [key, value] of Object.entries(expectedFields)) {
      if (response.data[key] !== value) {
        throw new Error(`Expected field ${key} to be ${value}, but got ${response.data[key]}`);
      }
    }
  }

  /**
   * 断言响应包含特定结构
   */
  static expectResponseStructure(response: { data: any }, structure: Record<string, any>): void {
    for (const key of Object.keys(structure)) {
      if (!(key in response.data)) {
        throw new Error(`Expected response to have key: ${key}`);
      }
    }
  }

  /**
   * 断言用户存在于数据库中
   */
  static async expectUserToExist(username: string): Promise<void> {
    const dataSource = await IntegrationTestDatabase.getDataSource();
    if (!dataSource) {
      throw new Error('Database not initialized');
    }

    const userRepository = dataSource.getRepository(UserEntity);
    const user = await userRepository.findOne({ where: { username } });

    if (!user) {
      throw new Error(`Expected user ${username} to exist in database`);
    }
  }

  /**
   * 断言用户不存在于数据库中
   */
  static async expectUserNotToExist(username: string): Promise<void> {
    const dataSource = await IntegrationTestDatabase.getDataSource();
    if (!dataSource) {
      throw new Error('Database not initialized');
    }

    const userRepository = dataSource.getRepository(UserEntity);
    const user = await userRepository.findOne({ where: { username } });

    if (user) {
      throw new Error(`Expected user ${username} not to exist in database`);
    }
  }
}