File size: 2,403 Bytes
21011e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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 };