const dbConnect = require('../configs/dbConnection');

async function checkPaymentAndOffer(bconnecttxnid) {
  // Check payment status and offer applied by joining upayments and offeruse
  const [rows] = await dbConnect.query(
    `SELECT up.uid, up.bconnecttxnid, up.status, ou.offercode, ul.ubal
     FROM upayments up
     JOIN ulogin ul ON ul.uid = up.uid
     JOIN offeruse ou ON ou.blk_ticket = up.validationid
     WHERE up.bconnecttxnid = ? 
       AND up.status = 'success' 
       AND ou.offercode = 'JOINBOBROS'`,
    [bconnecttxnid]
  );

  return rows.length > 0 ? rows[0] : null;
}

async function updateUserBalance({ bconnecttxnid, uid }) {
  // 1. Get payment and validationid
  const [paymentRows] = await dbConnect.query(
    'SELECT validationid, status FROM upayments WHERE bconnecttxnid = ?',
    [bconnecttxnid]
  );

  if (!paymentRows.length || paymentRows[0].status !== 'success') {
    throw new Error('Payment not successful or not found');
  }

  const validationid = paymentRows[0].validationid;

  // 2. Check offeruse for discount
  const [offerRows] = await dbConnect.query(
    'SELECT discount FROM offeruse WHERE blk_ticket = ? AND uid = ?',
    [validationid, uid]
  );

  if (!offerRows.length) {
    return { message: 'No offer used for this payment' };
  }

  const discount = offerRows[0].discount;

  // 3. Update balance
  await dbConnect.query(
    'UPDATE ulogin SET ubal = ubal + ? WHERE uid = ?',
    [discount, uid]
  );

  return { message: `Balance updated with discount ₹${discount}` };
}

module.exports = {
  checkPaymentAndOffer,
  updateUserBalance
};