// server.js

// --- Core Imports ---
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const path = require("path");

// --- Security Imports ---
const helmet = require("helmet");
const rateLimit = require("express-rate-limit");

// --- Route Imports (Organized by function) ---
// Public & Core
const authRoutes = require("./routes/authRoutes");
const roleRoutes = require("./routes/roleRoutes"); // Roles can be fetched by admins

// Institution-Level (for Admins/Staff)
const dashboardRoutes = require("./routes/dashboardRoutes");
const gradeRoutes = require("./routes/gradeRoutes");
const studentRoutes = require("./routes/studentRoutes");
const attendanceRoutes = require("./routes/attendanceRoutes");
const settingsRoutes = require("./routes/settingsRoutes");
const userRoutes = require("./routes/userRoutes"); // For an admin managing their staff

// Super Admin-Level
const institutionRoutes = require("./routes/institutionRoutes");
const planAndSubscriptionRoutes = require("./routes/planAndSubscriptionRoutes");
const superAdminRoutes = require("./routes/superAdminRoutes");

// --- App Initialization ---
const app = express();

// --- Core Middleware ---

// Enable CORS for all origins (adjust for production if needed)
app.use(cors());

// Set security-related HTTP headers
app.use(helmet());

// Body parser for JSON requests
app.use(express.json());

app.use("/assets", express.static(path.join(__dirname, "assets")));

// Rate Limiter: Apply to all API requests to prevent abuse
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // Limit each IP to 100 requests per windowMs
  standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
  legacyHeaders: false, // Disable the `X-RateLimit-*` headers
  message: {
    message:
      "Too many requests from this IP, please try again after 15 minutes",
  },
});
app.use("/api", limiter);

// --- API Route Mounting ---

// -- Public Routes --
// Authentication is the main public entry point
app.use("/api/auth", authRoutes);

// -- Institution-Level Routes (Protected for Admins/Staff) --
app.use("/api/dashboard", dashboardRoutes);
app.use("/api/grades", gradeRoutes);
app.use("/api/students", studentRoutes);
app.use("/api/attendance", attendanceRoutes);
app.use("/api/settings", settingsRoutes);
app.use("/api/users", userRoutes); // Scoped to an admin managing their own users
app.use("/api/roles", roleRoutes);

// -- Super Admin Routes (Highest Privilege) --
app.use("/api/institutions", institutionRoutes);
app.use("/api/platform-management", planAndSubscriptionRoutes); // Grouped plans & subs
app.use("/api/super-admin", superAdminRoutes);

// --- Health Check & Fallback Routes ---

// Root health check endpoint
app.get("/", (req, res) => {
  res.send("Attendance SAAS API is running and healthy...");
});

// 404 Not Found Handler for unhandled routes
// This must be after all other routes
app.use((req, res, next) => {
  res.status(404).json({ message: `Route not found: ${req.originalUrl}` });
});

// Central Error Handler
// Any error passed to `next(error)` in controllers will end up here
app.use((err, req, res, next) => {
  console.error("--- UNHANDLED ERROR ---");
  console.error(err.stack); // Log the full error stack for debugging

  // If the error is from Multer (e.g., file too large)
  if (err instanceof multer.MulterError) {
    return res
      .status(400)
      .json({ message: "File upload error", error: err.message });
  }

  // If it's another type of error
  if (err) {
    return res.status(500).json({
      message: "An internal server error occurred.",
      error: err.message,
    });
  }

  // If no error, just continue
  next();
});

// --- Server Startup ---
const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {
  console.log(
    `🚀 Server is running in ${
      process.env.NODE_ENV || "development"
    } mode on port ${PORT}`
  );
});
