const path = require("path");
const express = require("express");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const http = require("http");
const { Server } = require("socket.io");

const app = express();

/* =======================
   MIDDLEWARES
======================= */

app.use("/public", express.static("public"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());

app.use(
  cors({
    origin: ["http://localhost:3000", "http://192.168.1.73:3000"],
    credentials: true,
    methods: "GET,POST,PUT,PATCH,DELETE",
    allowedHeaders: "Content-Type,Authorization",
  })
);

/* =======================
   STATIC FILES
======================= */

app.use("/api/uploads", express.static(path.join(__dirname, "uploads")));
app.use("/api/public", express.static(path.join(__dirname, "public")));

/* =======================
   SOCKET.IO SETUP
======================= */

const server = http.createServer(app);

const io = new Server(server, {
  cors: {
    origin: ["http://localhost:3000", "http://192.168.1.73:3000"],
    credentials: true,
  },
});

app.use((req, res, next) => {
  req.io = io;
  next();
});

// Attach io to app for controllers/services
app.set("io", io);

io.on("connection", (socket) => {
  console.log("Socket connected:", socket.id);

  socket.on("join", (userId) => {
    if (!userId) return;
    socket.join(`user_${userId}`);
  });

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

/* =======================
   ROUTES (AFTER io SET)
======================= */

const authRouter = require("./routes/auth.routes");
const userRouter = require("./routes/user.routes");
const dashboardRouter = require("./routes/dashboard.routes");
const subjectRouter = require("./routes/subject.routes");
const enrollmentRouter = require("./routes/enrollment.routes");
const lessonRouter = require("./routes/lesson.routes");
const assignmentRouter = require("./routes/assignment.routes");
const submissionRouter = require("./routes/submission.routes");
const liveClassRouter = require("./routes/liveclass.routes");
const attendanceRouter = require("./routes/attendance.routes");
const paymentRouter = require("./routes/payment.routes");
const salaryRouter = require("./routes/salary.routes");
const notificationRouter = require("./routes/notification.routes");
const messageRouter = require("./routes/message.routes");
const contactRouter = require("./routes/contact.routes");
const feedbackRouter = require("./routes/feedback.routes");
const demoRoutes = require("./routes/demo.routes");
const testRouter = require("./routes/test.routes");

app.get("/", (req, res) => {
  res.send("LMS BACKEND RUNNING...");
});

app.get("/api/health", (req, res) => {
  res.json({ status: "ok" });
});

app.use("/api/v1/auth", authRouter);
app.use("/api/v1/users", userRouter);
app.use("/api/v1/dashboard", dashboardRouter);
app.use("/api/v1/subjects", subjectRouter);
app.use("/api/v1/enrollments", enrollmentRouter);
app.use("/api/v1/lessons", lessonRouter);
app.use("/api/v1/assignments", assignmentRouter);
app.use("/api/v1/submission", submissionRouter);
app.use("/api/v1/live-class", liveClassRouter);
app.use("/api/v1/attendance", attendanceRouter);
app.use("/api/v1/payments", paymentRouter);
app.use("/api/v1/salary", salaryRouter);
app.use("/api/v1/notification", notificationRouter);
app.use("/api/v1/message", messageRouter);
app.use("/api/v1/contact-us", contactRouter);
app.use("/api/v1/feedback", feedbackRouter);
app.use("/api/v1/demos", demoRoutes);
app.use("/test", testRouter);

/* =======================
   SERVER START
======================= */

const port = process.env.PORT || 5000;

server.listen(port, "0.0.0.0", () => {
  console.log(`Server + Socket.IO running on port ${port}`);
});
