import { DataSource } from 'typeorm';
import { beforeEach, afterEach } from 'vitest';
import { AppDataSource, EntityTarget, initializeDataSource } from '@d8d/shared-utils';

/**
 * 集成测试数据库工具类 - 使用真实PostgreSQL数据库
 * 通用版本，不依赖特定实体
 */
export class IntegrationTestDatabase {
  /**
   * 清理集成测试数据库
   */
  static async cleanup(): Promise<void> {
    if (AppDataSource.isInitialized) {
      await AppDataSource.destroy();
    }
  }

  /**
   * 获取当前数据源
   */
  static async getDataSource(): Promise<DataSource> {
    if (!AppDataSource.isInitialized) {
      await AppDataSource.initialize();
    }
    return AppDataSource;
  }

  /**
   * 使用特定实体初始化数据源
   */
  static async initializeWithEntities(entities: EntityTarget[]): Promise<DataSource> {
    initializeDataSource(entities);
    return await this.getDataSource();
  }
}

/**
 * 集成测试数据库生命周期钩子（带实体初始化）
 */
export function setupIntegrationDatabaseHooksWithEntities(entities: EntityTarget[]) {
  beforeEach(async () => {
    await IntegrationTestDatabase.initializeWithEntities(entities);
  });

  afterEach(async () => {
    await IntegrationTestDatabase.cleanup();
  });
}