const express = require('express');
const router = express.Router();
const branchController = require('../controllers/branchController');

const BranchInventory = require('../models/BranchInventory');
const Item = require('../models/Item');

// app.get('/api/branch-inventory', async (req, res) => {
//     try {
//       const { branchId } = req.query;
//       const inventory = await BranchInventory.find({ branchId }).populate('itemId', 'name code selling_price');
  
//       if (!inventory) {
//         return res.status(404).json({ message: 'No inventory found for this branch' });
//       }
  
//       res.json(inventory);
//     } catch (error) {
//       console.error('Error fetching branch inventory:', error);
//       res.status(500).json({ message: 'Error fetching inventory', error });
//     }
//   });



 

  
  // GET: Fetch branch inventory by branchId
  router.get('/all', async (req, res) => {


    
    const { branchId ,companyId} = req.query;
  




    // const getBranchInventories = async () => {
    //   try {
    //     const branchInventories = await BranchInventory.find({ branchId: branchId,companyId:companyId})
    //     .populate('itemId');

    //     // Handle the result
    
    //   } catch (err) {
    //     console.error('Error fetching branch inventory:', err);
    //   }
    // };
    
    // getBranchInventories();
    


    try {
      // Find all items in the inventory for the specified branch
   const inventory = await getItemsWithInventoryAndMinExpDate(branchId, companyId);
      
   //const inventory =await BranchInventory.find({ branchId: branchId,companyId:companyId }).populate('itemId');
  // const inventory = await BranchInventory.find({ branchId: branchId,companyId:companyId}).populate('itemId');








 //console.log("inventory",inventory);

  // inventory.forEach(item => {
   
  // //  totalSum += item.quantity * item.itemId.avg_price;
  // totalSum += item.quantity * (item.itemId && typeof item.itemId.avg_price === 'number' ? item.itemId.avg_price : 0);


  // });


//console.log("inv sum:",totalSum);


      res.status(200).json(inventory);
    } catch (error) {
      console.error('Error fetching branch inventory:', error);
      res.status(500).json({ message: 'Error fetching branch inventory' });
    }
  });
  


  router.get('/', async (req, res) => {
    const { branchId ,companyId,itemId} = req.query;
  
    try {
      // Find all items in the inventory for the specified branch
      const inventory = await BranchInventory.find({ branchId: branchId,companyId:companyId,itemId:itemId }).populate(' itemId');
      console.log(inventory);
      res.status(200).json(inventory);
    } catch (error) {
      console.error('Error fetching branch inventory:', error);
      res.status(500).json({ message: 'Error fetching branch inventory' });
    }
  });





  
  function getMinExpDate(expDates) {
      if (!expDates || expDates.length === 0) {
        return null; // Or handle the case where there are no expiration dates
      }
      console.log("exp date is:",expDates);
      const today = new Date();
      let minDays = Infinity;
      let minExpDate = null;
    
      for (const expDateObj of expDates) {
     
        const expDate = new Date(expDateObj.expDate);
        const timeLeft = expDate.getTime() - today.getTime();
        const daysLeft = Math.ceil(timeLeft / (1000 * 60 * 60 * 24));
    
        if (daysLeft < minDays) {
          minDays = daysLeft;
          minExpDate = expDate;
        }
      }
        if (minDays <= 0) {
            return "Expired"
        }
    
      return minExpDate;
    }
  




  


  async function getItemsWithInventoryAndMinExpDate(branchId, companyId) {
    try {
      const items = await Item.find({companyId:companyId } ).sort({code:1});
      const inventory = await BranchInventory.find({ branchId, companyId }).populate('itemId');
    
      if (!items || items.length === 0) {
        console.log("No items found");
        return [];
      }
  
      const combinedResults = items.map(item => {
        const sample={};
        let itemInventory={};
      itemInventory = inventory.find(inv => inv.itemId?._id.toString() === item?._id.toString()); // Find matching inventory
      //console.log("item is",item);
    

      if (Array.isArray(item.expDates) && item.expDates.length === 1 && item.expDates[0] === null) {
        console.log("expDates contains exactly [null]");
        item.expDates =  [];// to remove error locally but it does not change the value in database
    } else {
        console.log("expDates does not contain [null]");
    }
     const minExpDate = getMinExpDate(item.expDates);
  
        if (itemInventory) {
        //  itemInventory.minExpDate = minExpDate||"NA"; // Add minExpDate to inventory
   

          const plainInv = itemInventory.toObject();
          return {
            ...plainInv,
            minExpDate: minExpDate || "NA"
          };
    }
  

      // console.log("data is",itemInventory.toObject() )
      //  return itemInventory || null; 
      });
  
  
      return combinedResults;
    } catch (err) {
      console.error("Error:", err.message);
      throw err;
    }
  }
 
    
  module.exports = router;


  // async function getItemsWithMinExpDate() {
  //   try {
  //     const items = await Item.find();
  
  //     if (!items || items.length === 0) {
  //         console.log("No items found");
  //         return []; // Return empty array if no items found
  //     }
  
  //     const ItemsWIthMinimumExpDate = [];
  
  //     for (const item of items) {
  //       const minExpDate = getMinExpDate(item.expDates);
  //       //  if (minExpDate) {
  //             ItemsWIthMinimumExpDate.push({_id: item._id, minExpDate: minExpDate||''}); // Store as an object
  //        // }
  //     }
  
  //     console.log(ItemsWIthMinimumExpDate);
  //     return ItemsWIthMinimumExpDate; // Return the array
  //   } catch (err) {
  //     console.error("Error finding items:", err);
  //     throw err; // Re-throw the error for handling elsewhere if needed
  //   }
  // }