const serverService = require("../services/serverService");
const config = require("../config/config.js");

const register = async (req, res) => {
  try {
    const { name, url, secret, region, description } = req.body;

    if (secret !== process.env.GAME_SERVER_SECRET) {
      console.warn(`⚠️  Unauthorized registration attempt for server: ${name}`);
      return res.status(401).json({ message: "Unauthorized server" });
    }

    await serverService.registerGameServer({ name, url, region, description });
    res.json({ message: "Server registered successfully" });
  } catch (error) {
    console.error(`❌ Registration error: ${error.message}`);
    res.status(500).json({ message: "Internal server error" });
  }
};
const heartbeat = async (req, res) => {
  const { name, secret, playersOnline } = req.body;

  if (secret !== process.env.GAME_SERVER_SECRET) {
    return res.status(401).json({ message: "Unauthorized" });
  }
  try {
    await serverService.updateHeartbeat(name, playersOnline);
    res.json({ status: "ok" });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

const list = async (req, res) => {
  try {
    const servers = await serverService.getAvailableServers();
    res.json(servers);
  } catch (error) {
    res.status(500).json({ message: "Error fetching servers" });
  }
};
const join = async (req, res) => {
  try {
    const { serverId } = req.body;

    if (!serverId) {
      return res.status(400).json({ message: "Server ID is required" });
    }

    const server = await serverService.getServerConnectionDetails(serverId);
    if (!server) {
      return res.status(404).json({ message: "Server not found or offline" });
    }

    res.json({
      success: true,
      connectUrl: server.url,
      port: server.port,
      serverName: server.name,
      description: server.description,
      region: server.region,
    });
  } catch (error) {
    res.status(500).json({ message: "Error processing join request" });
  }
};

module.exports = {
  register,
  heartbeat,
  list,
  join,
};
