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

// Create a new Expense Group
exports.createExpenseGroup = async (req, res) => {
  try {
    const { groupName, companyId } = req.body;
    console.log("company:" + companyId);
    const newExpenseGroup = new ExpenseGroup({
      groupName,
      company: companyId
    });

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

// Get all Expense Groups for a specific company
exports.getExpenseGroups = async (req, res) => {
  try {
    const { companyId } = req.params;

    const expenseGroups = await ExpenseGroup.find({ company: companyId });
    res.status(200).json(expenseGroups);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
};

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

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

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

// Update an Expense Group
exports.updateExpenseGroup = async (req, res) => {
  try {
    const { id } = req.params;
    const { groupName, companyId } = req.body;

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

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

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

// Delete an Expense Group
exports.deleteExpenseGroup = async (req, res) => {
  try {
    const { id } = req.params;

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

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