const express = require('express');
const router = express.Router();
const db = require('../db');

router.post('/scan', (req, res) => {
  const { user_id, qr_code } = req.body;

  if (!user_id || !qr_code) {
    return res.status(400).json({ error: 'Missing user_id or qr_code' });
  }

  // 🔍 Extract redeem code if QR contains URL
  let redeemCode = qr_code;
  if (qr_code.includes('redeem=')) {
    redeemCode = qr_code.split('redeem=')[1];
  }

  // 🧾 Step 1: Verify redeem code in database
  const checkCodeSql = 'SELECT amount, used FROM redeem_codes WHERE code = ?';
  db.query(checkCodeSql, [redeemCode], (err, results) => {
    if (err) return res.status(500).json({ error: err });
    if (results.length === 0) return res.status(400).json({ error: 'Invalid redeem code' });

    const { amount, used } = results[0];
    if (used) return res.status(400).json({ error: 'This code has already been used' });

    // 🏦 Step 2: Ensure wallet exists
    const checkWalletSql = 'SELECT * FROM wallet WHERE user_id = ?';
    db.query(checkWalletSql, [user_id], (err2, walletResults) => {
      if (err2) return res.status(500).json({ error: err2 });

      const ensureWalletAndUpdate = () => {
        // 🏦 Step 3: Credit wallet balance
        const updateWalletSql = 'UPDATE wallet SET balance = balance + ? WHERE user_id = ?';
        db.query(updateWalletSql, [amount, user_id], (err3) => {
          if (err3) return res.status(500).json({ error: err3 });

          // 💳 Step 4: Record transaction
          const insertTransactionSql = `
            INSERT INTO transactions (user_id, type, amount)
            VALUES (?, 'credit', ?)
          `;
          db.query(insertTransactionSql, [user_id, amount, redeemCode], (err4) => {
            if (err4) return res.status(500).json({ error: err4 });

            // 🧾 Step 5: Mark code as used
            const markUsedSql = `
              UPDATE redeem_codes
              SET used = 1, used_by = ?, used_at = NOW()
              WHERE code = ?
            `;
            db.query(markUsedSql, [user_id, redeemCode], (err5) => {
              if (err5) return res.status(500).json({ error: err5 });

              res.json({
                success: true,
                message: '✅ Wallet credited successfully!',
                credited_amount: amount,
                code: redeemCode
              });
            });
          });
        });
      };

      // 🆕 If wallet doesn’t exist, create it first
      if (walletResults.length === 0) {
        const insertWalletSql = 'INSERT INTO wallet (user_id, balance) VALUES (?, 0)';
        db.query(insertWalletSql, [user_id], (err3) => {
          if (err3) return res.status(500).json({ error: err3 });
          ensureWalletAndUpdate();
        });
      } else {
        ensureWalletAndUpdate();
      }
    });
  });
});

module.exports = router;
