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

// Create a new bank account balance
exports.createBankAccountBalance = async (req, res) => {
  try {
    const { bankAccountId, balance } = req.body;

    const newBankAccountBalance = new BankAccountBalance({
      bankAccountId,
      balance
    });

    const savedBankAccountBalance = await newBankAccountBalance.save();
    res.status(201).json(savedBankAccountBalance);
  } catch (error) {
    console.error('Error creating bank account balance:', error);
    res.status(500).json({ message: 'Server error' });
  }
};

// Get all bank account balances
exports.getBankAccountBalances = async (req, res) => {
  try {
    const bankAccountBalances = await BankAccountBalance.find().populate('bankAccountId');
    res.status(200).json(bankAccountBalances);
  } catch (error) {
    console.error('Error fetching bank account balances:', error);
    res.status(500).json({ message: 'Server error' });
  }
};

// Get a specific bank account balance by ID
exports.getBankAccountBalanceById = async (req, res) => {
  try {
    const bankAccountBalance = await BankAccountBalance.findById(req.params.id).populate('bankAccountId');
    if (!bankAccountBalance) {
      return res.status(404).json({ message: 'Bank account balance not found' });
    }
    res.status(200).json(bankAccountBalance);
  } catch (error) {
    console.error('Error fetching bank account balance:', error);
    res.status(500).json({ message: 'Server error' });
  }
};

// Update a bank account balance
exports.updateBankAccountBalance = async (req, res) => {
  try {
    const updatedBankAccountBalance = await BankAccountBalance.findByIdAndUpdate(req.params.id, req.body, { new: true });
    if (!updatedBankAccountBalance) {
      return res.status(404).json({ message: 'Bank account balance not found' });
    }
    res.status(200).json(updatedBankAccountBalance);
  } catch (error) {
    console.error('Error updating bank account balance:', error);
    res.status(500).json({ message: 'Server error' });
  }
};

// Delete a bank account balance
exports.deleteBankAccountBalance = async (req, res) => {
  try {
    const deletedBankAccountBalance = await BankAccountBalance.findByIdAndDelete(req.params.id);
    if (!deletedBankAccountBalance) {
      return res.status(404).json({ message: 'Bank account balance not found' });
    }
    res.status(200).json({ message: 'Bank account balance deleted successfully' });
  } catch (error) {
    console.error('Error deleting bank account balance:', error);
    res.status(500).json({ message: 'Server error' });
  }
};
