const express = require('express');
const {authenticate, requirePermission} = require('../middleware/auth');
const permissionService = require('../services/permissionService');
const {asyncHandler} = require('../utils/asyncHandler');
const {success} = require('../utils/apiResponse');

const router = express.Router();

router.get('/', authenticate, requirePermission('privileges.view'), asyncHandler(async (req, res) => {
  const data = await permissionService.listPrivileges();
  return success(res, data);
}));

router.post('/', authenticate, requirePermission('privileges.manage'), asyncHandler(async (req, res) => {
  const data = await permissionService.saveRolePermissions(req.body.roleId, req.body.permissionKeys || []);
  return success(res, data, 'Permissions saved');
}));

module.exports = router;
