const express = require('express');
const router = express.Router();
const BranchInventory = require('../models/BranchInventory'); // Adjust the path as per your structure

router.put('/', async (req, res) => {
  try {
    // Destructure and validate request body
    const { branchId, itemId, quantity } = req.body;

    if (!branchId || !itemId || quantity === undefined) {
      return res.status(400).json({ error: "branchId, itemId, and quantity are required." });
    }

    // Update quantity in BranchInventory
    const updatedInventory = await BranchInventory.findOneAndUpdate(
      { branchId, itemId },       // Filter criteria
      { $set: { quantity: quantity } }, // Update operation
      { new: true, upsert: false }     // Return the updated document
    );

    if (!updatedInventory) {
      return res.status(404).json({ error: "Inventory item not found." });
    }

    // Send success response
    res.status(200).json({
      success: true,
      message: "Quantity updated successfully.",
      data: updatedInventory,
    });
  } catch (error) {
    console.error("Error updating inventory:", error.message);
    res.status(500).json({ error: "Internal server error." });
  }
});

module.exports = router;
