const express = require('express');
const router = express.Router();
const db = require('../db'); // your DB connection file

// ✅ Update withdraw (transaction) status
router.post('/', async (req, res) => {
  try {
    const { id, status } = req.body;

    if (!id || !status) {
      return res.status(400).json({
        success: false,
        message: 'Transaction ID and new status are required.'
      });
    }

    // Validate status value
    const validStatuses = ['Pending', 'Transfer'];
    if (!validStatuses.includes(status)) {
      return res.status(400).json({
        success: false,
        message: 'Invalid status value.'
      });
    }

    // Update transaction
    const [result] = await db.promise().query(
      'UPDATE transactions SET status = ? WHERE id = ?',
      [status, id]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({
        success: false,
        message: 'Transaction not found.'
      });
    }

    // ✅ Fetch updated transaction for confirmation
    const [updated] = await db.promise().query(
      'SELECT id, user_id, type, amount, status, created_at FROM transactions WHERE id = ?',
      [id]
    );

    res.json({
      success: true,
      message: `Transaction #${id} updated to ${status}`,
      data: updated[0],
    });
  } catch (error) {
    console.error('Error updating transaction status:', error);
    res.status(500).json({
      success: false,
      message: 'Internal Server Error',
      error: error.message,
    });
  }
});

module.exports = router;
