/**
 * 恢复 game_enter_server 脚本
 * 运行: node recover_enter_server.js
 * 会直接打印 INSERT 语句到控制台
 *
 * 依赖: mysql2, mongodb（项目已有，直接用 node_modules）
 */

const mysql = require('mysql2/promise');
const { MongoClient } = require('mongodb');

// ========== 配置 ==========
const MYSQL_CONFIG = {
  host: '127.0.0.1',
  port: 3306,
  user: 'root',
  password: 'wch123.com',
  database: 'sdk',
};
const MONGO_URL = 'mongodb://localhost:27017';
// ==========================

function escapeStr(str) {
  return String(str).replace(/\\/g, '\\\\').replace(/'/g, "\\'");
}

async function main() {
  const conn = await mysql.createConnection(MYSQL_CONFIG);

  const [servers] = await conn.query(`
    SELECT id, db_name, sid, tag, open_time
    FROM game_server
    WHERE tag = 11
      AND db_name IS NOT NULL
      AND db_name != ''
  `);

  if (servers.length === 0) {
    console.log('-- 未查询到 tag=11 的区服');
    await conn.end();
    return;
  }

  console.error(`找到 ${servers.length} 个 tag=11 区服，开始查询 MongoDB...`);

  const mongoClient = await MongoClient.connect(MONGO_URL);

  const inserts = [];

  for (const server of servers) {
    const { sid: serverId, db_name: dbName, tag, open_time: openTime } = server;

    let chars = [];
    try {
      chars = await mongoClient.db(dbName)
        .collection('char')
        .find({}, { projection: { newUniqueTag: 1, _id: 0 } })
        .toArray();
    } catch (e) {
      console.error(`[SKIP] ${dbName} 查询失败: ${e.message}`);
      continue;
    }

    console.error(`  [${dbName}] server_id=${serverId} 角色数=${chars.length}`);

    for (const char of chars) {
      const raw = char.newUniqueTag;
      if (!raw) continue;

      // newUniqueTag 格式: tag|sid|uid
      const parts = raw.split('|');
      const uid = parts[parts.length - 1];
      if (!uid) continue;
      const createTime = openTime && openTime > 0
        ? `FROM_UNIXTIME(${openTime})`
        : 'NOW()';

      inserts.push(
        `('${escapeStr(uid)}', '${serverId}', ${createTime}, '${serverId}', ${tag})`
      );
    }
  }

  await mongoClient.close();
  await conn.end();

  if (inserts.length === 0) {
    console.error('未找到任何角色数据');
    return;
  }

  console.error(`共生成 ${inserts.length} 条记录，输出 INSERT 语句：`);
  console.log('');
  console.log(`-- 恢复 game_enter_server，共 ${inserts.length} 条`);
  console.log('');

  // 每 500 条一批
  const batchSize = 500;
  for (let i = 0; i < inserts.length; i += batchSize) {
    const batch = inserts.slice(i, i + batchSize);
    console.log('INSERT INTO `game_enter_server` (`uid`, `server_id`, `create_time`, `first_server_id`, `tag`) VALUES');
    console.log(batch.join(',\n') + ';');
    console.log('');
  }
}

main().catch(err => {
  console.error('脚本执行失败:', err);
  process.exit(1);
});
