const { Router } = require("express");
const { authMiddleware } = require("../middlewares/auth.middleware");
const { authorizeRoles } = require("../middlewares/role.middleware");

const {
  getUsers,
  getUserById,
  updateUser,
  updateUserStatus,
  updateRole,
  deleteUser,
  getTeachers,
  getTeacherStudents,
  getAuditLogs,
  updateMyProfile,
  getMySecurityInfo, // new
  updateMyPassword,
} = require("../controllers/user.controller");

const userRouter = Router();

//only admin can manage user
userRouter.get(
  "/",
  authMiddleware,
  authorizeRoles("admin", "accountant"),
  getUsers
);
userRouter.get(
  "/teachers",
  authMiddleware,
  authorizeRoles("admin", "accountant"),
  getTeachers
);
userRouter.get(
  "/audit-logs",
  authMiddleware,
  authorizeRoles("admin", "accountant"),
  getAuditLogs
);
// ===== Security routes (new) =====
userRouter.get(
  "/me/security",   // GET last login
  authMiddleware,
  getMySecurityInfo
);
userRouter.post(
  "/me/security",   // POST update password
  authMiddleware,
  updateMyPassword
);
userRouter.patch("/me", authMiddleware, updateMyProfile);
userRouter.get(
  "/:id",
  authMiddleware,
  authorizeRoles("admin", "accountant"),
  getUserById
);
userRouter.patch(
  "/:id",
  authMiddleware,
  authorizeRoles("admin", "accountant"),
  updateUser
);
userRouter.patch(
  "/status/:id",
  authMiddleware,
  authorizeRoles("admin", "accountant"),
  updateUserStatus
);
userRouter.patch(
  "/role/:id",
  authMiddleware,
  authorizeRoles("admin", "accountant"),
  updateRole
);
userRouter.delete(
  "/delete/:id",
  authMiddleware,
  authorizeRoles("admin", "accountant"),
  deleteUser
);

userRouter.get(
  "/teacher/students",
  authMiddleware,
  authorizeRoles("teacher"),
  getTeacherStudents
);

module.exports = userRouter;
