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

// Create a new branch
exports.createBranch = async (req, res) => {
  try {
    const { companyId, name,type,groupId,
      storeBranchId ,
      considerStock,
      considerSystemSale,
    considerSystemWithdrawal,
    considerSystemWithdrawalForSelling,
    defaultAction


    } = req.body;


console.log("body data is:", req.body)

    // Step 1: Create the branch
    const newBranch = new Branch({ companyId, name,
      type,groupId,storeBranchId ,
      considerStock,
      considerSystemSale,
    considerSystemWithdrawal,
    considerSystemWithdrawalForSelling,
    defaultAction });
 
    const savedBranch = await newBranch.save();

    // Step 2: Initialize inventory for the new branch for all company items
    const items = await Item.find({ companyId: companyId });
    const inventoryPromises = items.map(item => {
      return BranchInventory.create({
        companyId,
        branchId: savedBranch._id,
        itemId: item._id,
        quantity: 0 // Initial quantity set to 0
      });
    });
    
    await Promise.all(inventoryPromises);
console.log("creeeeeeeeeeeeeeted")
    res.status(201).json({ success: true, branch: savedBranch, message: 'Branch created and inventory initialized.' });
  } catch (error) {
    console.error('Error creating branch and initializing inventory:', error);
    res.status(500).json({ message: 'Error creating branch and initializing inventory', error });
  }
};



// Get all branches (optionally by companyId)
exports.getBranches = async (req, res) => {
  try {
    const { companyId } = req.query;
    
    let branches;


      branches = await Branch.find({ companyId }).populate('companyId').populate("groupId");
   
    res.status(200).json(branches);
   
 
  } catch (error) {
    res.status(500).json({ message: 'Error retrieving branches', error });
  }
};

// Update a branch
exports.updateBranch = async (req, res) => {


  try {
    const { id } = req.params;
    const { companyId, name,type,groupId,
      storeBranchId,
      considerStock,
      considerSystemSale,
    considerSystemWithdrawal, considerSystemWithdrawalForSelling,defaultAction} = req.body;
    const updatedBranch = await Branch.findByIdAndUpdate(
      id,
      { companyId, name,type ,groupId,storeBranchId,
        considerStock,
        considerSystemSale,
      considerSystemWithdrawal, considerSystemWithdrawalForSelling,defaultAction},
      { new: true }
    );

    if (!updatedBranch) {
      return res.status(404).json({ message: 'Branch not found' });
    }

    res.status(200).json(updatedBranch);
  } catch (error) {
    res.status(500).json({ message: 'Error updating branch', error });
  }
};

// Delete a branch
exports.deleteBranch = async (req, res) => {
  try {
    const { id } = req.params;
    const deletedBranch = await Branch.findByIdAndDelete(id);

    if (!deletedBranch) {
      return res.status(404).json({ message: 'Branch not found' });
    }

    res.status(200).json({ message: 'Branch deleted successfully' });
  } catch (error) {
    res.status(500).json({ message: 'Error deleting branch', error });
  }
};
