import express from 'express';
import { authenticate } from '../middleware/authMiddleware.js';
import { authorize, requireAdmin } from '../middleware/authorizationMiddleware.js';
import permissionController from '../controllers/permissionController.js';

const router = express.Router();

// Middleware to disable caching for permission routes
const noCache = (req, res, next) => {
  res.set('Cache-Control', 'no-store, no-cache, must-revalidate, private');
  res.set('Pragma', 'no-cache');
  res.set('Expires', '0');
  next();
};

// Apply no-cache to all routes
router.use(noCache);

// Get available roles (no club context needed)
router.get('/roles/available', authenticate, permissionController.getAvailableRoles);

// Get permission structure (no club context needed)
router.get('/structure/all', authenticate, permissionController.getPermissionStructure);

// Get and manage club roles
router.get('/:clubId/roles', authenticate, authorize('permissions', 'read'), permissionController.getClubRoles);
router.post('/:clubId/roles', authenticate, authorize('permissions', 'write'), permissionController.createClubRole);
router.put('/:clubId/roles/:roleId', authenticate, authorize('permissions', 'write'), permissionController.updateClubRole);
router.delete('/:clubId/roles/:roleId', authenticate, authorize('permissions', 'write'), permissionController.deleteClubRole);

// Get current user's permissions for a club (no authorization check - needed to load permissions)
router.get('/:clubId', authenticate, permissionController.getUserPermissions);

// Get all club members with their permissions (admin only)
router.get('/:clubId/members', authenticate, authorize('permissions', 'read'), permissionController.getClubMembersWithPermissions);

// Update user role (admin only)
router.put('/:clubId/user/:userId/role', authenticate, authorize('permissions', 'write'), permissionController.updateUserRole);
router.put('/:clubId/user/:userId/roles', authenticate, authorize('permissions', 'write'), permissionController.updateUserRoles);

// Update user permissions (admin only)
router.put('/:clubId/user/:userId/permissions', authenticate, authorize('permissions', 'write'), permissionController.updateUserPermissions);

// Update user status (admin only)
router.put('/:clubId/user/:userId/status', authenticate, authorize('permissions', 'write'), permissionController.updateUserStatus);

export default router;
