const express = require("express");
const router = express.Router();
const dataCenterController = require("../controllers/dataCenterController");

router.get("/nearest-datacenter/:ip", async (req, res) => {
  try {
    const clientIp = req.params.ip;

    console.log(clientIp);

    const nearestDC = await dataCenterController.getNearestDataCenter(clientIp);

    if (nearestDC !== null) {
      res.json({ nearest_data_center: nearestDC });
    } else {
      res
        .status(500)
        .json({ error: "Unable to determine nearest data center" });
    }
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal server error" });
  }
});

router.get("/all-datacenters", async (req, res) => {
  try {
    const pingResults = await dataCenterController.getAllPingResults();
    const formattedResults = JSON.stringify(
      { ping_results: pingResults },
      null,
      2
    );
    res.type("json").send(formattedResults);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal server error" });
  }
});

module.exports = router;
