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 { PaymentEntity } from "./modules/payments/payment.entity"
import { MembershipPlan } from "./modules/membership/membership-plan.entity"
import { Template } from "./modules/templates/template.entity"
import { InitSystemSettings1735900000000 } from "./migrations/1735900000000-init-system-settings"
import { SystemSetting } from "./modules/settings/system-setting.entity"
import { SolutionDesign } from "./modules/solution-designs/solution-design.entity"
import { SolutionChapter } from "./modules/solution-designs/solution-chapter.entity"

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

const dataSource = isTestEnv && testDatabaseUrl
  ? new DataSource({
      type: "mysql",
      url: testDatabaseUrl,
      entities: [
        User, Role, File, PaymentEntity, MembershipPlan, Template, SystemSetting,
        SolutionDesign, SolutionChapter,
      ],
      migrations: [
        InitSystemSettings1735900000000,
      ],
      synchronize: true, // 测试环境总是同步schema
      dropSchema: true,  // 测试环境每次重新创建schema
      logging: false,    // 测试环境关闭日志
    })
  : new DataSource({
      type: "mysql",
      host: process.env.DB_HOST || "localhost",
  port: parseInt(process.env.DB_PORT || "3306"),
  username: process.env.DB_USERNAME || "root",
      password: process.env.DB_PASSWORD || "",
  database: process.env.DB_DATABASE || "d8dai",
      entities: [
        User, Role, File, PaymentEntity, MembershipPlan, Template, SystemSetting,
        SolutionDesign, SolutionChapter,
      ],
      migrations: [
        InitSystemSettings1735900000000,
      ],
      synchronize: process.env.DB_SYNCHRONIZE !== "false",
      logging: process.env.DB_LOGGING === "true",
    });

export const AppDataSource = dataSource;
