const { checkPaymentAndOffer, updateUserBalance } = require('../model/paymentModel');

async function handleUpdateBalance(req, res, next) {
  try {
    const { bconnecttxnid, amountToAdd } = req.body;

    if (!bconnecttxnid || typeof amountToAdd !== 'number') {
      return res.status(400).json({ success: false, message: 'Missing or invalid fields.' });
    }

    const paymentRecord = await checkPaymentAndOffer(bconnecttxnid);

    if (!paymentRecord) {
      return res.status(404).json({
        success: false,
        message: 'No successful payment found with JOINBOBROS offer for this transaction.'
      });
    }

    const newBalance = parseFloat(paymentRecord.ubal) + amountToAdd;

    const updated = await updateUserBalance(paymentRecord.uid, newBalance);

    if (!updated) {
      return res.status(500).json({ success: false, message: 'Failed to update user balance.' });
    }

    return res.status(200).json({
      success: true,
      message: `Balance updated successfully.`,
      newBalance
    });

  } catch (err) {
    next(err);
  }
}

module.exports = { handleUpdateBalance };