import "reflect-metadata"
import { DataSource, EntitySchema } from "typeorm"
import process from 'node:process'

// 实体目标类型，可以是类、函数或实体模式
export type EntityTarget = Function | EntitySchema<any> | string

/**
 * 创建数据源配置
 * @param entities 实体类数组
 * @returns DataSource 实例
 */
export function createDataSource(entities: EntityTarget[]): DataSource {
  // 在测试环境下使用测试数据库配置
  const isTestEnv = process.env.NODE_ENV === 'test';
  const testDatabaseUrl = process.env.TEST_DATABASE_URL || 'postgresql://postgres:test_password@localhost:5432/test_d8dai';

  return isTestEnv && testDatabaseUrl
    ? new DataSource({
        type: "postgres",
        url: testDatabaseUrl,
        entities,
        migrations: [],
        synchronize: true, // 测试环境总是同步schema
        dropSchema: true,  // 测试环境每次重新创建schema
        logging: false,    // 测试环境关闭日志
      })
    : new DataSource({
        type: "postgres",
        host: process.env.DB_HOST || "localhost",
        port: parseInt(process.env.DB_PORT || "5432"),
        username: process.env.DB_USERNAME || "postgres",
        password: process.env.DB_PASSWORD || "",
        database: process.env.DB_DATABASE || "postgres",
        entities,
        migrations: [],
        synchronize: process.env.DB_SYNCHRONIZE !== "false",
        logging: process.env.DB_LOGGING === "true",
      });
}

/**
 * 默认数据源实例（需要传入实体）
 * 注意：这个实例需要在具体模块中传入实体类
 */
export let AppDataSource: DataSource;

/**
 * 初始化默认数据源
 * @param entities 实体类数组
 */
export function initializeDataSource(entities: EntityTarget[]): void {
  AppDataSource = createDataSource(entities);
}