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

// 实体类导入
import { UserEntity as User } from "./modules/users/user.entity"
import { Role } from "./modules/users/role.entity"
import { File } from "./modules/files/file.entity"
import { ActivityEntity } from "./modules/activities/activity.entity"
import { RouteEntity } from "./modules/routes/route.entity"
import { AreaEntity } from "./modules/areas/area.entity"
import { LocationEntity } from "./modules/locations/location.entity"

// 在测试环境下使用测试数据库配置
const isTestEnv = process.env.NODE_ENV === 'test';
const testDatabaseUrl = process.env.TEST_DATABASE_URL || 'postgresql://postgres:test_password@localhost:5432/test_d8dai';
;

const dataSource = isTestEnv && testDatabaseUrl
  ? new DataSource({
      type: "postgres",
      url: testDatabaseUrl,
      entities: [User, Role, File, ActivityEntity, RouteEntity, AreaEntity, LocationEntity],
      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: [User, Role, File, ActivityEntity, RouteEntity, AreaEntity, LocationEntity],
      migrations: [],
      synchronize: process.env.DB_SYNCHRONIZE !== "false",
      logging: process.env.DB_LOGGING === "true",
    });

export const AppDataSource = dataSource;