const BranchGroup = require('../models/BranchGroup');

// Create a new Branch Group
exports.createBranchGroup = async (req, res) => {
  try {
    const { groupName, companyId } = req.body;
    console.log("company:"+companyId);
    const newBranchGroup = new BranchGroup({
      groupName,
      company: companyId
    });

    await newBranchGroup.save();
    res.status(201).json({ message: 'Branch group created successfully', newBranchGroup });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
};

// Get all Branch Groups for a specific company
exports.getBranchGroups = async (req, res) => {
  try {
    const { companyId } = req.params;
 
    const branchGroups = await BranchGroup.find({ company: companyId });
    res.status(200).json(branchGroups);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
};

// Get a single Branch Group by ID
exports.getBranchGroupById = async (req, res) => {
  try {
    const { id } = req.params;

    const branchGroup = await BranchGroup.findById(id);
    if (!branchGroup) {
      return res.status(404).json({ message: 'Branch group not found' });
    }

    res.status(200).json(branchGroup);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
};

// Update a Branch Group
exports.updateBranchGroup = async (req, res) => {
  try {
    const { id } = req.params;
    const { groupName, companyId } = req.body;

    const updatedBranchGroup = await BranchGroup.findByIdAndUpdate(
      id,
      { groupName, company: companyId },
      { new: true, runValidators: true }
    );

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

    res.status(200).json({ message: 'Branch group updated successfully', updatedBranchGroup });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
};

// Delete a Branch Group
exports.deleteBranchGroup = async (req, res) => {
  try {
    const { id } = req.params;

    const deletedBranchGroup = await BranchGroup.findByIdAndDelete(id);
    if (!deletedBranchGroup) {
      return res.status(404).json({ message: 'Branch group not found' });
    }

    res.status(200).json({ message: 'Branch group deleted successfully' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
};
