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

// 🔹 Get wallet + transactions by user_id
router.get('/:user_id', (req, res) => {
  const { user_id } = req.params;

  // Fetch wallet balance and transaction list in one response
  const walletSql = 'SELECT balance FROM wallet WHERE user_id = ?';
  const txSql = 'SELECT id, type, amount,  DATE_FORMAT(created_at, "%d %b %Y") AS date FROM transactions WHERE user_id=? ORDER BY id DESC';

  db.query(walletSql, [user_id], (err, walletResults) => {
    if (err) return res.status(500).json({ error: err });

    const balance = walletResults.length ? walletResults[0].balance : 0;

    db.query(txSql, [user_id], (err2, txResults) => {
      if (err2) return res.status(500).json({ error: err2 });

      res.json({
        balance,
        transactions: txResults
      });
    });
  });
});

module.exports = router;
