const { company } = require('../config/permission');
const Branch = require('../models/Branch'); // Adjust the path to your Branch model
const BranchInventory = require('../models/BranchInventory'); // Adjust the path to your BranchInventory model
const { getTotalSummary, get_Total_Summary } = require('./getTotalSummaryController');



const getSummary= async (companyId,branchId,currentDate) => {   // this shall be for all company and per company. at night for all company. but at request per company
    // Fetch all branches and process them
let date=currentDate|| new Date();
    try {
      // Fetch all branches
const _id=branchId;
      
      let branches;
    console.log("company and brach id are:",companyId+"__"+branchId);


      if (companyId && branchId) {
        branches = await Branch.find({ companyId,_id });
      } else if (branchId) {
        branches = await Branch.find({ _id });
      } else if (companyId) {
        branches = await Branch.find({ companyId });
      } else {
        branches = await Branch.find();
      }
      

      if (branches.length === 0) {
        throw new Error('No branches found.');
      }
  
console.log("branches are",branches);

   
      const branchResults = await Promise.all(branches.map(async (branch) => {
        const branchId = branch._id;
        const companyId = branch.companyId; // Assuming companyId exists in Branch model
        const branchType=branch.type;
  

        // Fetch inventory for the branch
        const inventory = await BranchInventory.find({ branchId }).populate('itemId');
  
        // Calculate total sum for the branch
        let totalBranchSum = 0;
        inventory.forEach(item => {
          
          const avgPrice=item.itemId?.avg_price||0;
           totalBranchSum += item.quantity *avgPrice;
        });
  
       // console.log("total brach sum is",totalBranchSum);
      const totalSummary= await get_Total_Summary(companyId,branchId,date);
      //  console.log("each total summary:",totalSummary);

        // Return result with branchId, companyId, branchName, and totalBranchSum
        return {
          branchId,
          companyId, 
          branchName: branch.name, // Assuming `name` exists in Branch model
          totalBranchSum,
           totalSummary// inside this there are total sale ,storeWithdrwal total purchase , total expense total deposit and total withdraw
        };
      }));
  
    
      // Return the list of branches with their total sums
      return  branchResults ;
     
  
    } catch (error) {
      console.error('Error fetching branch inventories:', error);
      throw error; // Rethrow error for the caller to handle
    }
  };
  


// Export the function
module.exports = {
    getSummary,
  };