const { MongoClient } = require("mongodb"); let dbClient = null; let dbInstance = null; let cache = null; let isSaving = false; let needsSave = false; const DEFAULT_DB = { users: {}, // { userId: { username, coins, characters: [], totalWins } } customCharacters: [], // admin-added characters sessions: {}, // { chatId: session data } }; async function initDB() { const uri = process.env.MONGODB_URI; if (!uri) { console.error("❌ MONGODB_URI not set in environment!"); process.exit(1); } try { console.log("🔌 Connecting to MongoDB..."); dbClient = new MongoClient(uri); await dbClient.connect(); dbInstance = dbClient.db(); console.log("✅ Successfully connected to MongoDB."); const collection = dbInstance.collection("bot_state"); const record = await collection.findOne({ _id: "state" }); if (record) { cache = record.data; console.log("✅ Loaded bot state from MongoDB cache."); } else { cache = JSON.parse(JSON.stringify(DEFAULT_DB)); await collection.insertOne({ _id: "state", data: cache }); console.log("✅ Created initial bot state in MongoDB."); } } catch (err) { console.error("❌ Failed to connect or initialize MongoDB:", err); process.exit(1); } } function loadDB() { if (!cache) { // Return temporary default during fallback return JSON.parse(JSON.stringify(DEFAULT_DB)); } return cache; } function saveDB(db) { cache = db; queueSave(); } function queueSave() { if (isSaving) { needsSave = true; return; } isSaving = true; const collection = dbInstance.collection("bot_state"); collection.updateOne( { _id: "state" }, { $set: { data: cache } }, { upsert: true } ).then(() => { isSaving = false; console.log("💾 Bot state successfully synchronized to MongoDB."); if (needsSave) { needsSave = false; queueSave(); } }).catch((err) => { console.error("❌ MongoDB background sync error:", err); isSaving = false; }); } function getUser(db, userId, username) { if (!db.users[userId]) { db.users[userId] = { username: username || `User${userId}`, coins: 0, characters: [], totalWins: 0, }; } else if (username) { db.users[userId].username = username; } return db.users[userId]; } module.exports = { initDB, loadDB, saveDB, getUser };