import { DataSource } from 'typeorm';
import { config } from '../config/index.js';
import { User } from './entities/User.js';
import { UserToken } from './entities/UserToken.js';
import { SystemConfig } from './entities/SystemConfig.js';
import { AccountGroup } from './entities/AccountGroup.js';
import { PlatformAccount } from './entities/PlatformAccount.js';
import { PublishTask } from './entities/PublishTask.js';
import { PublishResult } from './entities/PublishResult.js';
import { Comment } from './entities/Comment.js';
import { AnalyticsData } from './entities/AnalyticsData.js';
import { OperationLog } from './entities/OperationLog.js';
import { Work } from './entities/Work.js';
import { WorkDayStatistics } from './entities/WorkDayStatistics.js';
import { UserDayStatistics } from './entities/UserDayStatistics.js';

export const AppDataSource = new DataSource({
  type: 'mysql',
  host: config.database.host,
  port: config.database.port,
  username: config.database.username,
  password: config.database.password,
  database: config.database.database,
  // 永远关闭 synchronize：避免自动改表/删列（统一走 migrations）
  synchronize: false,
  logging: config.env === 'development',
  entities: [
    User,
    UserToken,
    SystemConfig,
    AccountGroup,
    PlatformAccount,
    PublishTask,
    PublishResult,
    Comment,
    AnalyticsData,
    OperationLog,
    Work,
    WorkDayStatistics,
    UserDayStatistics,
  ],
  charset: 'utf8mb4',
});

export async function initDatabase(): Promise<DataSource> {
  if (!AppDataSource.isInitialized) {
    await AppDataSource.initialize();
  }
  return AppDataSource;
}

export {
  User,
  UserToken,
  SystemConfig,
  AccountGroup,
  PlatformAccount,
  PublishTask,
  PublishResult,
  Comment,
  AnalyticsData,
  OperationLog,
  Work,
  WorkDayStatistics,
  UserDayStatistics,
};
