const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const { createServer } = require("http");
const { Server } = require("socket.io");

const dotenv = require("dotenv");

if (process.env.NODE_ENV) {
  dotenv.config({
    path: `.env.${process.env.NODE_ENV}`,
  });
} else {
  dotenv.config();
}

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
  path: '/api/socket.io',
  cors: {
    origin: true,
    credentials: true,
  },
});

const connectDB = require("./db");
const gridCellsRouter = require("./routes/gridCells");

gridCellsRouter.setIO(io);

// connect database
connectDB();

app.use(
  cors({
    origin: true,
    credentials: true,
  })
);

app.use(express.json());

// Socket.IO
io.on("connection", (socket) => {
  console.log(`Socket connected: ${socket.id}`);

  socket.on("disconnect", () => {
    console.log(`Socket disconnected: ${socket.id}`);
  });
});

app.get("/api/test", (req, res) => {
  console.log("Hey");
  res.json({ message: "Hello from backend!" });
});

app.use("/api/grid-cells", gridCellsRouter);

app.get("/api/status", (req, res) => {
  const mem = process.memoryUsage();
  const uptime = Math.floor(process.uptime());
  const hours = Math.floor(uptime / 3600);
  const minutes = Math.floor((uptime % 3600) / 60);

  mongoose.connection.readyState === 1
    ? res.json({
        status: "online",
        uptime: `${hours}h ${minutes}m`,
        memory: {
          rss: `${(mem.rss / 1024 / 1024).toFixed(1)} MB`,
          heapUsed: `${(mem.heapUsed / 1024 / 1024).toFixed(1)} MB`,
        },
        mongo: "connected",
      })
    : res.json({
        status: "online",
        uptime: `${hours}h ${minutes}m`,
        memory: {
          rss: `${(mem.rss / 1024 / 1024).toFixed(1)} MB`,
          heapUsed: `${(mem.heapUsed / 1024 / 1024).toFixed(1)} MB`,
        },
        mongo: "disconnected",
      });
});

const PORT = process.env.PORT || 5000;
httpServer.listen(PORT, () => {
  console.log("Server running on port 5000");
});
