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

async function applyBBPSOffer({ pmobile, uid, pemail, validationid, totalAmount, offerCode }) {

  const maxDiscount = 25;

  // ✅ Check if user already made previous successful BBPS payment
  // Exclude current validationid to avoid false positives
  const [rows] = await dbConnect.query(
    `SELECT COUNT(*) AS count
     FROM upayments
     WHERE (tmobile = ? OR temail = ?)
       AND status = 'success'
       AND validationid != ?`,
    [pmobile, pemail, validationid]
  );

  const alreadyUsed = rows[0].count > 0;

  if (offerCode === 'JOINBOBROS') {

    // ❗ First-time user check
    if (alreadyUsed) {
      return {
        success: false,
        message: 'Offer valid only for first-time BBPS users.'
      };
    }

    // ❗ Minimum amount check
    if (totalAmount <= 25) {
      return {
        success: false,
        message: 'Offer applicable only for amount greater than ₹25.'
      };
    }

    // ✅ Calculate discount (10% capped at maxDiscount)
    let discount = totalAmount * 0.10;
    if (discount > maxDiscount) discount = maxDiscount;

    const newTotal = +(totalAmount - discount).toFixed(2);

    // ✅ Done — no separate offer table needed; just return result
    return {
      success: true,
      message: `₹${discount} discount applied successfully.`,
      discount,
      newTotal
    };

  } else {
    return {
      success: false,
      message: 'Invalid offer code.'
    };
  }
}

module.exports = { applyBBPSOffer };