const express = require('express');
const multer = require('multer');
const router = express.Router();
const verifyToken = require('../middlewares/verifyToken');
const {
    getAllTickets,
    getTicketById,
    createTicket,
    updateTicket,
    deleteTicket,
    closeTicket
} = require('../controllers/ticketsController');

const upload = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: 10 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    const allowed = /^image\/|^video\/|application\/pdf$/i;
    if (allowed.test(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error('Only images, video, and PDF are allowed.'), false);
    }
  }
});

const handleMulterError = (err, req, res, next) => {
  if (err instanceof multer.MulterError) {
    if (err.code === 'LIMIT_FILE_SIZE') {
      return res.status(400).json({ success: false, message: 'File too large. Max 10 MB per file.' });
    }
    if (err.code === 'LIMIT_FILE_COUNT') {
      return res.status(400).json({ success: false, message: 'Too many files. Max 5 attachments.' });
    }
  }
  if (err && err.message === 'Only images, video, and PDF are allowed.') {
    return res.status(400).json({ success: false, message: err.message });
  }
  next(err);
};

router.get('/', verifyToken, getAllTickets);
router.get('/:id', verifyToken, getTicketById);
router.post('/', verifyToken, upload.array('attachments', 5), handleMulterError, createTicket);
router.put('/:id/close', verifyToken, closeTicket);
router.put('/:id', verifyToken, updateTicket);
router.delete('/:id', verifyToken, deleteTicket);

module.exports = router;

