const express = require("express");

const router = express.Router();

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

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


// 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();
};

// User management
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);


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

module.exports = router;
