const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const {
  getAllCategories,
  getCategoryById,
  createCategory,
  updateCategory,
  toggleCategoryStatus,
  deleteCategory,
  getCategoryStatistics,
  searchCategories,
  getActiveCategories
} = require('../controllers/categoriesController');

// Ensure upload directory exists
const uploadDir = path.join(__dirname, '../uploads/categories');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// Configure multer for file uploads
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, 'category-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const fileFilter = (req, file, cb) => {
  // Check file type
  if (file.mimetype.startsWith('image/')) {
    cb(null, true);
  } else {
    cb(new Error('Only image files are allowed!'), false);
  }
};

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB limit
  },
  fileFilter: fileFilter
});

// Get all categories
router.get('/', getAllCategories);

// Get active categories - using a more specific path to avoid conflicts
router.get('/list/active', getActiveCategories);

// Search categories
router.get('/search', searchCategories);

// Get category statistics
router.get('/analytics/statistics', getCategoryStatistics);

// Get category by ID - must come after all other GET routes
router.get('/:id', getCategoryById);

// Create new category
router.post('/', upload.single('image'), createCategory);

// Update category
router.put('/:id', upload.single('image'), updateCategory);

// Toggle category status
router.patch('/:id/toggle-status', toggleCategoryStatus);

// Delete category (hard delete)
router.delete('/:id', deleteCategory);

module.exports = router; 