import { Router, Request, Response, NextFunction } from 'express';
import toolConfigController from '../controllers/toolConfig.controller';
import { authenticate } from '../middleware/auth.middleware';
import { requirePermission } from '../middleware/rbac.middleware';

const router = Router();

const TOOL_PERMISSION_MAP: Record<string, string> = {
  bookstack: 'wissen:configure',
  vikunja: 'vikunja:configure',
  nextcloud: 'nextcloud:configure',
};

/**
 * Middleware that resolves the permission from the :tool param
 * and delegates to requirePermission().
 */
function requireToolPermission(req: Request, res: Response, next: NextFunction): void {
  const tool = req.params.tool as string;
  const permission = TOOL_PERMISSION_MAP[tool];
  if (!permission) {
    res.status(400).json({ success: false, message: 'Unbekanntes Tool' });
    return;
  }
  requirePermission(permission)(req, res, next);
}

router.get('/config/:tool', authenticate, requireToolPermission, toolConfigController.getConfig.bind(toolConfigController));
router.put('/config/:tool', authenticate, requireToolPermission, toolConfigController.updateConfig.bind(toolConfigController));
router.post('/config/:tool/test', authenticate, requireToolPermission, toolConfigController.testConnection.bind(toolConfigController));

export default router;
