import 'dotenv/config';
import * as fs from 'fs';
import * as path from 'path';
import { createConnection } from 'mysql2/promise';

async function main() {
  const host = process.env.DB_HOST || '127.0.0.1';
  const port = Number(process.env.DB_PORT || 3306);
  const user = process.env.DB_USERNAME || 'root';
  const password = process.env.DB_PASSWORD || '';
  const database = process.env.DB_DATABASE || 'wwjcloud';

  console.log(`[db:init] Connecting to MySQL ${host}:${port} as ${user}`);
  const conn = await createConnection({
    host,
    port,
    user,
    password,
    multipleStatements: true,
    charset: 'utf8mb4'
  });

  console.log(`[db:init] Ensuring database exists: ${database}`);
  await conn.query(
    `CREATE DATABASE IF NOT EXISTS \`${database}\` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,
  );
  await conn.query(`USE \`${database}\``);

  const sqlPath = path.resolve(__dirname, '../../../sql/wwjcloud.sql');
  console.log(`[db:init] Loading SQL from: ${sqlPath}`);
  const sqlRaw = fs.readFileSync(sqlPath, 'utf8');
  // 处理 UTF-8 BOM 与首行 SET NAMES，避免 mysql2 解析错误
  let sql = sqlRaw.replace(/^\uFEFF/, '');
  sql = sql.replace(/^\s*SET\s+NAMES\s+utf8mb4\s*;\s*/i, '');

  console.log('[db:init] Executing SQL... (this may take a while)');
  await conn.query(sql);

  console.log('[db:init] Done.');
  await conn.end();
}

main().catch((err) => {
  console.error('[db:init] Failed:', err?.message || err);
  process.exit(1);
});