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

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

  // 1️⃣ Check KYC status in kyc_details table
  db.query('SELECT status FROM kyc_details WHERE user_id = ?', [user_id], (err, kycResult) => {
    if (err) return res.status(500).json({ error: err });

    if (!kycResult || kycResult.length === 0) {
      return res.status(404).json({ 
        message: 'KYC details not found for this user', 
        kycStatus: null 
      });
    }

    const kycStatus = kycResult[0].status;
    
    // 🔹 Print KYC status to console

    if (kycStatus !== 'Approved') {
      return res.status(400).json({ 
        message: 'KYC not approved. Withdrawal not allowed.', 
        kycStatus 
      });
    }

    // 2️⃣ Check wallet balance
    db.query('SELECT balance FROM wallet WHERE user_id = ?', [user_id], (err, walletResult) => {
      if (err) return res.status(500).json({ error: err });

      if (!walletResult || walletResult.length === 0) {
        return res.status(404).json({ 
          message: 'Wallet not found for this user', 
          kycStatus 
        });
      }

      const balance = walletResult[0].balance;

      if (balance === null || balance === 0) {
        return res.status(400).json({ 
          message: 'Balance not available', 
          kycStatus 
        });
      }

      if (balance < amount) {
        return res.status(400).json({ 
          message: 'Insufficient balance', 
          kycStatus 
        });
      }

      // 3️⃣ Deduct balance and record transaction
      db.query('UPDATE wallet SET balance = balance - ? WHERE user_id = ?', [amount, user_id], (err) => {
        if (err) return res.status(500).json({ error: err, kycStatus });

        db.query(
          'INSERT INTO transactions (user_id, type, amount,status) VALUES (?, ?, ?,?)',
          [user_id, 'debit', amount,'Pending'],
          (err) => {
            if (err) return res.status(500).json({ error: err, kycStatus });
            
            res.json({ 
              message: 'Withdrawal successful', 
              kycStatus 
            });
          }
        );
      });
    });
  });
});

module.exports = router;
