import express from "express";
import {
  getAllRoles,
  getRoleById,
  createRole,
  updateRole,
  deleteRole,
  getAllPermissions,
  assignRoleToUser,
  removeRoleFromUser,
  getUserPermissions,
  updateRolePermissions,
  checkUserPermission,
  getAuditLogs,
} from "./rbac.controller";
import { isAuthenticated, hasPermission, hasMinLevel } from "../../middlewares/auth";
import { hasRole } from "../../middlewares/rbac";

const router = express.Router();

// Public routes (limited access)
router.get("/permissions", getAllPermissions);
router.get("/users/:user_id/permissions/check", checkUserPermission);

// Admin routes (require authentication and admin permissions)
router.get("/roles", isAuthenticated, hasPermission("system.manage_roles"), getAllRoles);
router.get("/roles/:role_id", isAuthenticated, hasPermission("system.manage_roles"), getRoleById);
router.post("/roles", isAuthenticated, hasPermission("system.manage_roles"), createRole);
router.put("/roles/:role_id", isAuthenticated, hasPermission("system.manage_roles"), updateRole);
router.delete("/roles/:role_id", isAuthenticated, hasPermission("system.manage_roles"), deleteRole);

// Role assignment routes
router.post("/assign", isAuthenticated, hasPermission("user.manage_roles"), assignRoleToUser);
router.post("/remove", isAuthenticated, hasPermission("user.manage_roles"), removeRoleFromUser);

// User permissions routes
router.get("/users/:user_id/permissions", isAuthenticated, hasPermission("user.manage_roles"), getUserPermissions);
router.put("/roles/:role_id/permissions", isAuthenticated, hasPermission("system.manage_permissions"), updateRolePermissions);

// Audit logs (super admin only)
router.get("/audit", isAuthenticated, hasMinLevel(100), getAuditLogs);

// Alternative permission checks using role-based middleware
router.get("/admin/test", isAuthenticated, hasRole("admin"), (req, res) => {
  res.json({ message: "Admin access granted" });
});

router.get("/super-admin/test", isAuthenticated, hasRole("super_admin"), (req, res) => {
  res.json({ message: "Super admin access granted" });
});

router.get("/moderator/test", isAuthenticated, hasRole("moderator"), (req, res) => {
  res.json({ message: "Moderator access granted" });
});

export default router;