const express = require('express');
const router = express.Router();
const upload = require('../config/multer'); // Import multer config






const { getAllItems, createItem, updateItem, deleteItem } = require('../controllers/itemController');
const { getItemDetails,getCombinedData } = require('../controllers/itemDetailsController'); // Import the new controller



const { bulkImportItems } = require('../controllers/itemController');

// Route for bulk importing items
router.post('/import', bulkImportItems);
//router.get('/bulk-import', bulkImportItems);
// GET all items for a company
router.get('/', getAllItems);

// Route to handle item creation with image upload
router.post('/', upload.single('image'), createItem);

// DELETE an item
router.delete('/:itemId', deleteItem);

// GET: Fetch details for a specific item
router.get('/:itemId/details', getItemDetails);

router.get('/:itemId/detailsAndTransfer', getCombinedData);


const Item = require('../models/Item'); // Adjust the path to your model

router.put('/bulkEdit', async (req, res) => {
  try {
    const { itemId, companyId, avg_price, selling_price,lowStock,name,code } = req.body;

if(lowStock) // first check if the update is for stock level

{

  const updatedItem = await Item.findOneAndUpdate(
    { _id: itemId,companyId:companyId }, // Find by itemId and branchId
    { $set: { lowStock } }, 
    { new: true } // Return the updated document
  );


  if (!updatedItem) {
    return res.status(404).json({ success: false, message: 'Item not found' });
  }

  // Respond with success
   return res.status(200).json({ success: true, message: 'Item updated successfully', data: updatedItem });


}


if(code) // check if the update is name or code

{

  const updatedItem = await Item.findOneAndUpdate(
    { _id: itemId,companyId:companyId }, // Find by itemId and branchId
    { $set: { name,code} }, 
    { new: true } // Return the updated document
  );


  if (!updatedItem) {
    return res.status(404).json({ success: false, message: 'Item not found' });
  }

  // Respond with success
   return res.status(200).json({ success: true, message: 'Item updated successfully', data: updatedItem });


}



    // Validate input
    if (!itemId || !avg_price || !selling_price) {
      return res.status(400).json({ success: false, message: 'Missing required fields' });
    }

    // Update the item in the database
    const updatedItem = await Item.findOneAndUpdate(
      { _id: itemId,companyId:companyId }, // Find by itemId and branchId
      { $set: { avg_price, selling_price } }, // Update avg_price and selling_price
      { new: true } // Return the updated document
    );




    if (!updatedItem) {
      return res.status(404).json({ success: false, message: 'Item not found' });
    }

    // Respond with success
    res.status(200).json({ success: true, message: 'Item updated successfully', data: updatedItem });
  } catch (error) {
    console.error('Error updating item:', error.message);
    res.status(500).json({ success: false, message: 'Server error during bulk edit' });
  }
});


// PUT update an existing item
router.put('/:itemId',upload.single('image'), updateItem);





module.exports = router;
