const express = require('express');
const router = express.Router();
const {
  getBanners,
  getBanner,
  createBanner,
  updateBanner,
  deleteBanner,
  bannerPhotoUpload,
  getActiveBanners
} = require('../controllers/bannerController');
const { auth: protect, authorize } = require('../middleware/auth');
const uploadBannerImage = require('../middleware/bannerUpload');

// Public routes
router.get('/active', getActiveBanners);
router.get('/:id', getBanner);

// Apply protect middleware to all routes below
router.use(protect);

// Apply admin authorization to all routes below
router.use((req, res, next) => {
  console.log('Authorizing admin access for banners route');
  return authorize('admin')(req, res, next);
});

// Protected admin routes
router.route('/')
  .get(getBanners)
  .post(createBanner);

// Handle both PUT and PATCH for banner updates
router.route('/:id')
  .put(updateBanner)
  .patch(updateBanner)
  .delete(deleteBanner);

// Banner photo upload route - handles both PUT and PATCH for photo upload
const uploadPhotoMiddleware = [
  (req, res, next) => {
    console.log('Starting banner photo upload for banner ID:', req.params.id);
    next();
  },
  uploadBannerImage,
  (req, res, next) => {
    if (!req.file && !req.uploadedFile) {
      return next(new ErrorResponse('No file was uploaded', 400));
    }
    console.log('Banner photo uploaded successfully:', req.uploadedFile || req.file);
    next();
  },
  bannerPhotoUpload
];

// Handle both PUT and PATCH for photo upload
router.put('/:id/photo', ...uploadPhotoMiddleware);
router.patch('/:id/photo', ...uploadPhotoMiddleware);

module.exports = router;
