const express = require('express');
const router = express.Router();
const TicketController = require('../controllers/ticket.controller');
const { authenticateToken } = require('../middleware/auth');
const { requireAdmin, canViewTickets, canModifyTickets } = require('../middleware/roleCheck');

// SSE-Endpoint: kein authenticateToken (Token via ?token= Query-Param)
router.get('/:id/events', TicketController.streamComments);

// Public endpoints (no auth required)
router.get('/:id/feedback', TicketController.feedback);
router.post('/:id/feedback', TicketController.submitFeedback);
router.post('/public', TicketController.createPublic);

// All other ticket routes require authentication
router.use(authenticateToken);

router.get('/stats',   canViewTickets, TicketController.getStats);
router.get('/metrics', canViewTickets, TicketController.getMetrics);
router.get('/routing', requireAdmin,   TicketController.getRouting);
router.post('/routing', requireAdmin,  TicketController.saveRouting);
router.get('/',        canViewTickets, TicketController.getAll);
router.get('/:id',     canViewTickets, TicketController.getById);

// All authenticated users can create tickets
router.post('/', TicketController.create);

// Bulk-Update (Staff only)
router.put('/bulk', canModifyTickets, TicketController.bulkUpdate);

router.put('/:id',           canModifyTickets, TicketController.update);
router.put('/:id/snooze',    canModifyTickets, TicketController.snooze);
router.delete('/:id',        requireAdmin,     TicketController.delete);

// Comments
router.post('/:id/comments',                        TicketController.addComment);
router.post('/:id/ai-reply',                        TicketController.aiReply);
router.delete('/:id/comments/:commentId', canModifyTickets, TicketController.deleteComment);

// History
router.get('/:id/history', canViewTickets, TicketController.getHistory);

// PDF export
router.get('/:id/pdf', canViewTickets, TicketController.exportPdf);

// Links
router.get('/:id/links',          canViewTickets,    TicketController.getLinks);
router.post('/:id/links',         canModifyTickets,  TicketController.addLink);
router.delete('/:id/links/:linkId', canModifyTickets, TicketController.removeLink);

// Assignees
router.post('/:id/assignees',           canModifyTickets, TicketController.addAssignee);
router.delete('/:id/assignees/:userId', canModifyTickets, TicketController.removeAssignee);

module.exports = router;
