require("dotenv").config();
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const path = require("path")

const adminBatchRoutes = require("./routes/admin/batch");
const adminClassRoutes = require("./routes/admin/class");
const adminSubjectRoutes = require("./routes/admin/Subject");
const adminCourseRoutes = require("./routes/admin/course");
const adminLectureRoutes = require("./routes/admin/lecture");
const adminChapterRoutes = require("./routes/admin/chapter");
const adminTopicRoutes = require("./routes/admin/topic");
const userCourseRoutes = require("./routes/user/course");
const userLectureRoutes = require("./routes/user/lecture");
const userChapterRoutes = require("./routes/user/chapter");
const userTopicRoutes = require("./routes/user/topic");
const userAuthRoutes = require("./routes/user/auth");
const adminEnrollmentRoutes = require("./routes/admin/enrollment");
const userEnrollmentRoutes = require("./routes/user/Uenrollment");
const requireAdmin = require("./middleware/requireAdmin");
const adminUsers = require("./routes/admin/users");

const app = express();

app.use(cors({
  origin: ["http://127.0.0.1:5500", "http://localhost:5500", "http://localhost:5173"],
  methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
  allowedHeaders: ["Content-Type", "Authorization", "x-admin", "x-admin-key"]
}));

app.use(express.json());

async function startServer() {
  try {
    await mongoose.connect(process.env.MONGO_URI);
    console.log("MongoDB connected successfully");

    // PUBLIC (NO TOKEN)
    app.use("/api/user", userCourseRoutes);
    app.use("/api/user", userChapterRoutes);
    app.use("/api/user", userLectureRoutes);
    app.use("/api/user", userTopicRoutes);

    // USER AUTH (NO ADMIN TOKEN)
    app.use("/api/auth", userAuthRoutes);

    // ADMIN LOGIN (NO TOKEN REQUIRED)
    app.use("/api/admin", require("./routes/admin/adminAuth"));

    // ADMIN (JWT REQUIRED)
    app.use("/api/admin", requireAdmin, adminBatchRoutes);
    app.use("/api/admin", requireAdmin, adminClassRoutes);
    app.use("/api/admin", requireAdmin, adminSubjectRoutes);
    app.use("/api/admin", requireAdmin, adminCourseRoutes);
    app.use("/api/admin", requireAdmin, adminLectureRoutes);
    app.use("/api/admin", requireAdmin, adminChapterRoutes);
    app.use("/api/admin", requireAdmin, adminTopicRoutes);
    app.use("/api/admin", requireAdmin, adminEnrollmentRoutes);

    // UPLOAD THUMBNAIL
    app.use("/uploads", express.static(path.join(__dirname, "uploads")))

    //AdminUsers
    app.use("/api/admin/users", adminUsers)
    
    app.get("/", (req, res) => {
      res.send("Backend server is working!");
    });

    app.listen(5000, '0.0.0.0', () => {
      console.log(`Server running on 0.0.0.0:5000`);
    });
  } catch (error) {
    console.error("MongoDB connection failed:", error);
  }
}

startServer();
