const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { auth, authorize } = require('../middleware/auth');
const { catchAsync } = require('../middleware/errorHandler');
const {
  getAllItems,
  getItemById,
  createItem,
  updateItem,
  deleteItem,
  getItemsByCategory,
  searchItems,
  updateItemStock,
  bulkUploadItems,
  bulkUpdateItems,
  bulkEditItems,
  downloadTemplate,
  downloadBulkEditTemplate,
  downloadBulkUploadTemplate,
  exportItems,
  getItemStockMovements
} = require('../controllers/itemsController');

// Configure multer for file uploads (bulk operations) using memory storage
const memoryStorage = multer.memoryStorage();

// File filter function for bulk operations (Excel and CSV)
const bulkFileFilter = (req, file, cb) => {
  console.log('Processing file upload:', {
    originalname: file.originalname,
    mimetype: file.mimetype,
    size: file.size,
    fieldname: file.fieldname
  });

  // Define allowed MIME types for Excel and CSV
  const allowedMimeTypes = [
    // Excel MIME types
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
    'application/vnd.ms-excel', // .xls
    'application/octet-stream', // Sometimes files come with this mime type
    'application/vnd.ms-office', // Generic MS Office mime type
    'application/zip', // XLSX is actually a zip file
    // CSV MIME types
    'text/csv',
    'application/csv',
    'text/plain', // CSV files are often served as text/plain
    'text/x-csv',
    'application/x-csv',
    'text/comma-separated-values',
    'text/x-comma-separated-values'
  ];
  
  const fileExt = path.extname(file.originalname).toLowerCase();
  const allowedExtensions = ['.xlsx', '.xls', '.csv'];
  
  // Log more details for debugging
  console.log('File validation:', {
    originalname: file.originalname,
    mimetype: file.mimetype,
    extension: fileExt,
    allowedMimeType: allowedMimeTypes.includes(file.mimetype),
    allowedExtension: allowedExtensions.includes(fileExt)
  });
  
  // Check if the file is empty
  if (file.size === 0) {
    const error = new Error('File is empty');
    console.error('File upload rejected:', error.message);
    return cb(error, false);
  }
  
  // Check file extension and MIME type
  const isValidMimeType = allowedMimeTypes.includes(file.mimetype);
  const isValidExtension = allowedExtensions.includes(fileExt);
  
  if ((isValidMimeType || fileExt === '.csv') && isValidExtension) {
    console.log('File accepted:', file.originalname);
    return cb(null, true);
  } else {
    const error = new Error(`Invalid file type. Only Excel (.xlsx, .xls) and CSV (.csv) files are allowed. Received: ${file.mimetype}, ${fileExt}`);
    console.error('File upload rejected:', error.message);
    return cb(error, false);
  }
}

// Initialize multer upload for bulk operations
const upload = multer({ 
  storage: memoryStorage,
  fileFilter: bulkFileFilter,
  limits: {
    fileSize: 10 * 1024 * 1024, // 10MB limit
    files: 1,
    fieldSize: 10 * 1024 * 1024 // 10MB max file size
  },
  onError: function(err, next) {
    console.error('Multer error:', err);
    next(err);
  }
});

// Create image upload directory if it doesn't exist
const imageUploadDir = path.join(__dirname, '../uploads/items');
if (!fs.existsSync(imageUploadDir)) {
  fs.mkdirSync(imageUploadDir, { recursive: true });
  console.log(`Created directory: ${imageUploadDir}`);
} else {
  console.log(`Using existing directory: ${imageUploadDir}`);
}

const imageStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, imageUploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname).toLowerCase();
    cb(null, 'item-' + uniqueSuffix + ext);
  }
});

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

const uploadItemImage = multer({
  storage: imageStorage,
  fileFilter: imageFileFilter,
  limits: {
    fileSize: 5 * 1024 * 1024
  }
});

// Error handling middleware for file uploads
const handleUploadError = (err, req, res, next) => {
  if (err instanceof multer.MulterError) {
    // A Multer error occurred when uploading
    return res.status(400).json({
      success: false,
      msg: `File upload error: ${err.message}`
    });
  } else if (err) {
    // An unknown error occurred
    return res.status(400).json({
      success: false,
      msg: err.message || 'Error uploading file'
    });
  }
  // No error, proceed to next middleware
  next();
};

// @desc    Get all items with pagination, search, and filters
// @route   GET /
// @access  Public
router.get('/', catchAsync(getAllItems));

// @desc    Get items by category
// @route   GET /category/:categoryId
// @access  Public
router.get('/category/:categoryId', catchAsync(getItemsByCategory));

// @desc    Search items
// @route   GET /search
// @access  Public
router.get('/search', catchAsync(searchItems));

// @desc    Get single item by ID
// @route   GET /:id
// @access  Public
router.get('/:id', catchAsync(getItemById));

// @desc    Create a new item
// @route   POST /
// @access  Private/Admin, Store Manager
router.post('/', auth, authorize('admin', 'store_manager'), uploadItemImage.array('images', 10), catchAsync(createItem));

// @desc    Update an item
// @route   PUT /:id
// @access  Private/Admin, Store Manager
router.put('/:id', auth, authorize('admin', 'store_manager'), uploadItemImage.array('images', 10), catchAsync(updateItem));

// @desc    Delete an item (soft delete)
// @route   DELETE /:id
// @access  Private/Admin, Store Manager
router.delete('/:id', auth, authorize('admin', 'store_manager'), catchAsync(deleteItem));

// @desc    Update item stock
// @route   PATCH /:id/stock
// @access  Private/Admin, Store Manager
router.patch('/:id/stock', auth, authorize('admin', 'store_manager'), catchAsync(updateItemStock));

// @desc    Get item stock movements
// @route   GET /:id/movements
// @access  Private/Admin
router.get('/:id/movements', auth, authorize('admin'), catchAsync(getItemStockMovements));
// @desc    Download Excel template for bulk upload
// @route   GET /template/download
// @access  Private/Admin
router.get('/template/download', auth, authorize('admin'), catchAsync(downloadTemplate));
// @route   GET /bulk-edit/template
// @access  Private/Admin
router.get(
  '/bulk-edit/template',
  auth,
  authorize('admin'),
  catchAsync(downloadBulkEditTemplate)
);

// @desc    Bulk edit items
// @route   POST /bulk-edit
// @access  Private/Admin
router.post(
  '/bulk-edit',
  auth,
  authorize('admin'),
  upload.single('file'),
  handleUploadError,
  catchAsync(bulkEditItems)
);

// @desc    Bulk upload items from Excel/CSV
// @route   POST /bulk-upload
// @access  Private/Admin
router.post(
  '/bulk-upload',
  auth,
  authorize('admin'),
  upload.single('file'),
  handleUploadError,
  catchAsync(bulkUploadItems)
);

// @desc    Bulk update items
// @route   PUT /bulk-update
// @access  Private/Admin
router.put('/bulk-update', 
  auth, 
  authorize('admin'),
  // Use multer with no field name restrictions
  (req, res, next) => {
    console.log('Bulk update route hit');
    console.log('Request headers:', req.headers);
    
    // Create a new multer instance for this specific request
    const uploadAny = multer({
      storage: memoryStorage,
      fileFilter: bulkFileFilter,
      limits: {
        fileSize: 10 * 1024 * 1024, // 10MB limit
        files: 1
      }
    }).any(); // Accept any field name
    
    uploadAny(req, res, function(err) {
      if (err) {
        console.error('Multer error:', err);
        return res.status(400).json({ 
          success: false, 
          msg: 'File upload error',
          error: err.message 
        });
      }
      
      if (!req.files || req.files.length === 0) {
        console.error('No files received in request');
        return res.status(400).json({ 
          success: false, 
          msg: 'No file uploaded' 
        });
      }
      
      // Get the first file (we only expect one)
      const file = req.files[0];
      console.log('File received successfully:', {
        originalname: file.originalname,
        mimetype: file.mimetype,
        size: file.size,
        fieldname: file.fieldname
      });
      
      // Add the file to req.file for backward compatibility
      req.file = file;
      
      // Proceed to the bulk update handler
      next();
    });
  },
  handleUploadError, 
  catchAsync(bulkUpdateItems)
);

// @desc    Export current items data
// @route   GET /export
// @access  Private/Admin
router.get('/export', auth, authorize('admin'), catchAsync(exportItems));

// @desc    Download bulk upload template
// @route   GET /bulk-upload/template
// @access  Private/Admin
router.get(
  '/bulk-upload/template',
  auth,
  authorize('admin'),
  catchAsync(downloadBulkUploadTemplate)
);

module.exports = router;