require("dotenv").config();
const express = require("express");
const cors = require("cors");
const path = require("path");
const rateLimit = require("express-rate-limit");

const sequelize = require("./config/database");
const languageMiddleware = require("./middleware/language");
const contentRoutes = require("./routes/content");
const chatbotRoutes = require("./routes/chatbot");
const adminRoutes = require("./admin/router");

const app = express();
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "..", "views"));

// --- CORS (équivalent CORS_ALLOWED_ORIGINS) -----------------------------
const allowedOrigins = (process.env.ALLOWED_ORIGINS || "http://localhost:3000").split(",");
app.use(cors({ origin: allowedOrigins }));

app.use(express.json());
app.use(languageMiddleware);

// --- Throttle global (équivalent DEFAULT_THROTTLE_RATES "anon": "60/min") ---
app.use("/api/", rateLimit({ windowMs: 60 * 1000, max: 60 }));

// --- Fichiers médias (images/documents uploadés, équivalent MEDIA_URL) ---
app.use(process.env.MEDIA_URL || "/media/", express.static(path.join(__dirname, "..", "media")));

// --- API publique ---------------------------------------------------------
app.use("/api/v1", contentRoutes);
if (process.env.ENABLE_CHATBOT === "true") {
  app.use("/api/v1/chatbot", chatbotRoutes);
}

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

// --- Interface d'administration (équivalent /admin/ Django) ---------------
app.use("/admin", adminRoutes);

async function start() {
  await sequelize.authenticate();
  console.log("Connexion MySQL établie. - server.js:43");

  const port = process.env.PORT || 8000;
  app.listen(port, () => {
    console.log(`Serveur igf.bi (Node) démarré sur le port ${port} - server.js:47`);
    console.log(`Admin disponible sur http://localhost:${port}/admin - server.js:48`);
  });
}

start().catch((err) => {
  console.error("Échec du démarrage du serveur : - server.js:53", err);
  process.exit(1);
});
