const express = require("express");

const router = express.Router();

/* ************************************************************************* */
// Define Your API Routes Here
/* ************************************************************************* */

// Import Controllers
const userControllers = require("./controllers/userControllers");
const authControllers = require("./controllers/authControllers");
const saveControllers = require("./controllers/saveControllers");
const verifyToken = require("./middlewares/verifyToken");
const verifyOAuth = require("./middlewares/verifyOAuth");

// Vérifie que le token appartient au même utilisateur que :id
const verifySelf = (req, res, next) => {
  if (String(req.user) !== String(req.params.id)) {
    return res.status(403).json({ message: "Forbidden." });
  }
  return next();
};

// Auth SuperOAuth
router.get("/auth/callback", authControllers.callback);
router.post("/auth/logout", authControllers.logout);

// User management (auth locale — conservée pendant migration)
router.get("/users", verifyToken, userControllers.browse);
router.get("/users/:id", verifyToken, verifySelf, userControllers.read);
router.get("/users/:id/field", verifyToken, verifySelf, userControllers.read);
router.put("/users/:id", verifyToken, verifySelf, userControllers.edit);
router.post("/users", userControllers.add);
router.delete("/users/:id", verifyToken, verifySelf, userControllers.destroy);
router.post("/login", userControllers.login);

// Sync game state — SuperOAuth uniquement
router.patch("/users/:id/coins", verifyOAuth, verifySelf, userControllers.updateCoins);

// Game saves — JWT required
router.get("/save", verifyToken, saveControllers.load);
router.post("/save", verifyToken, saveControllers.save);


/* ************************************************************************* */

module.exports = router;
