const express = require('express');
const multer = require('multer');
const path = require('path');
const { authenticate, authorize } = require('../middleware/auth');
const ScheduleController = require('../controllers/ScheduleController');

const router = express.Router();

const scheduleStorage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, path.join(__dirname, '..', 'uploads')),
  filename: (req, file, cb) => {
    const uniqueName = `schedule_${req.params.id}_${Date.now()}${path.extname(file.originalname)}`;
    cb(null, uniqueName);
  },
});
const scheduleUpload = multer({
  storage: scheduleStorage,
  fileFilter: (req, file, cb) => {
    const allowed = /jpeg|jpg|png|gif|webp/;
    const extOk = allowed.test(path.extname(file.originalname).toLowerCase());
    const mimeOk = allowed.test(file.mimetype.split('/')[1]);
    cb(null, extOk && mimeOk);
  },
  limits: { fileSize: 5 * 1024 * 1024 },
});

router.get('/upcoming', ScheduleController.getUpcoming);
router.get('/', authenticate, authorize('admin', 'manager'), ScheduleController.getAll);
router.get('/:id', ScheduleController.getById);
router.post('/', authenticate, authorize('admin', 'manager'), ScheduleController.create);
router.put('/:id', authenticate, authorize('admin', 'manager'), ScheduleController.update);
router.delete('/:id', authenticate, authorize('admin'), ScheduleController.delete);
router.post('/:id/image', authenticate, authorize('admin', 'manager'), scheduleUpload.single('image'), ScheduleController.uploadImage);

module.exports = router;
