const express = require("express");
const cors = require("cors");
const Gamedig = require("gamedig");

const app = express();
const port = 3000;

app.use(cors());

const servers = [
  { ip: "45.235.98.67", port: 27030 },
  { ip: "45.235.98.67", port: 27031 },
  { ip: "45.235.98.67", port: 27032 },
  { ip: "45.235.98.67", port: 27033 },
  { ip: "45.235.98.67", port: 27034 },
];

let cachedResults = [];

// Actualiza el estado de todos los servidores cada 2 minutos
async function updateServerStatuses() {
  const results = await Promise.all(
    servers.map(async ({ ip, port }) => {
      try {
        const state = await Gamedig.query({
          type: "cs16",
          host: ip,
          port: port,
        });
        return {
          name: state.name,
          ip: `${ip}:${port}`,
          map: state.map,
          players: state.players.length,
          maxPlayers: state.maxplayers,
          online: true,
        };
      } catch {
        return {
          name: "Servidor sin conexión",
          ip: `${ip}:${port}`,
          map: "-",
          players: 0,
          maxPlayers: 0,
          online: false,
        };
      }
    })
  );

  cachedResults = results;
  console.log("Estados actualizados:", new Date().toLocaleTimeString());
}

// Primera actualización al iniciar y luego cada 2 minutos
updateServerStatuses();
setInterval(updateServerStatuses, 2 * 60 * 1000);

app.get("/servers", (req, res) => {
  res.json(cachedResults);
});

app.listen(port, () => {
  console.log(`Servidor corriendo en http://localhost:${port}`);
});

