const GameServer = require("../models/GameServer");

const registerGameServer = async (serverData) => {
  const { name, url, region, description } = serverData;

  const server = await GameServer.findOneAndUpdate(
    { name },
    {
      url,
      lastHeartbeat: Date.now(),
      status: "online",
      description,
      region,
    },
    { upsert: true, returnDocument: "after" },
  );

  console.log(`📡 [REGISTRY] Game Server "${name}" at ${url} is now ONLINE`);
  return server;
};
const updateHeartbeat = async (name, playersOnline) => {
  return await GameServer.findOneAndUpdate(
    { name },
    {
      lastHeartbeat: Date.now(),
      status: "online",
      playersOnline: playersOnline,
    },
  );
};

const checkServerHealth = async () => {
  const timeout = new Date(Date.now() - 60000);

  const result = await GameServer.updateMany(
    { lastHeartbeat: { $lt: timeout }, status: "online" },
    { status: "offline" },
  );

  if (result.modifiedCount > 0) {
    console.log(`[CLEANUP] Marked ${result.modifiedCount} servers as OFFLINE`);
  }
};

const getAvailableServers = async () => {
  return await GameServer.find({}).select(
    "name url playersOnline status maxPlayers",
  );
};
const getServerConnectionDetails = async (serverId) => {
  return await GameServer.findOne({ _id: serverId, status: "online" }).select(
    "name url port region description",
  );
};
setInterval(checkServerHealth, 60000);

module.exports = {
  registerGameServer,
  updateHeartbeat,
  getAvailableServers,
  getServerConnectionDetails,
};
