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';

const MYSQL_CHINA_TIMEZONE = '+08:00';

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',
  timezone: MYSQL_CHINA_TIMEZONE,
  entities: [
    User,
    UserToken,
    SystemConfig,
    AccountGroup,
    PlatformAccount,
    PublishTask,
    PublishResult,
    Comment,
    AnalyticsData,
    OperationLog,
    Work,
    WorkDayStatistics,
    UserDayStatistics,
  ],
  charset: 'utf8mb4',
});

let timezoneHookInstalled = false;

async function ensureMysqlSessionTimezone(): Promise<void> {
  try {
    await AppDataSource.query(`SET time_zone = '${MYSQL_CHINA_TIMEZONE}'`);
  } catch {
    return;
  }

  if (timezoneHookInstalled) return;

  const driver: any = AppDataSource.driver as any;
  const pool: any = driver?.pool;

  if (pool && typeof pool.on === 'function') {
    pool.on('connection', (connection: any) => {
      connection.query(`SET time_zone = '${MYSQL_CHINA_TIMEZONE}'`);
    });
    timezoneHookInstalled = true;
  }
}

async function ensurePublishTasksPublishProxyColumn(): Promise<void> {
  try {
    const rows: Array<{ cnt: number }> = await AppDataSource.query(
      `SELECT COUNT(*) AS cnt
       FROM information_schema.COLUMNS
       WHERE TABLE_SCHEMA = ?
         AND TABLE_NAME = 'publish_tasks'
         AND COLUMN_NAME = 'publish_proxy'`,
      [config.database.database]
    );

    const cnt = Number(rows?.[0]?.cnt || 0);
    if (cnt > 0) return;

    await AppDataSource.query(
      `ALTER TABLE publish_tasks
       ADD COLUMN publish_proxy JSON NULL AFTER platform_configs`
    );
  } catch {
    return;
  }
}

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

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