const express = require('express'); const router = express.Router(); const { getConnection, getUserAccounts, getUserCards, getUserTransfers, setAccountBalance, getAccount, addTransfer } = require('../libs/mysql'); const { checkAuth } = require('../libs/middlewares'); router.post('/', checkAuth, async (req, res) => { const user = req.user; res.send(user); }); router.post('/accounts', checkAuth, async (req, res) => { const user = req.user; const connection = await getConnection(); const accounts = await getUserAccounts(connection, user.id); connection.end(); res.send(accounts); }); router.post('/cards', checkAuth, async (req, res) => { const user = req.user; const connection = await getConnection(); const cards = await getUserCards(connection, user.id); connection.end(); res.send(cards); }); router.post('/transfers', checkAuth, async (req, res) => { const user = req.user; const connection = await getConnection(); const transfers = await getUserTransfers(connection, user.id); connection.end(); res.send(transfers); }); router.post('/send-money', checkAuth, async (req, res) => { const user = req.user; const { account_from_id, account_to_id, amount, name } = req.body; if (!account_from_id || !account_to_id || !amount || !name) { return res.status(400).send({ error: 'Missing required fields' }); } const connection = await getConnection(); const accountFrom = await getAccount(connection, account_from_id); const accountTo = await getAccount(connection, account_to_id); if (!accountFrom[0] || !accountTo[0]) { return res.status(400).send({ error: 'Invalid account ID' }); } if (accountFrom[0].client_id !== user.id) { return res.status(403).send({ error: 'You are not authorized to send money from this account' }); } if (accountFrom[0].balance < amount) { return res.status(400).send({ error: 'Insufficient funds' }); } await setAccountBalance(connection, account_from_id, accountFrom[0].balance - amount); await setAccountBalance(connection, account_to_id, accountTo[0].balance + amount); await addTransfer(connection, account_from_id, account_to_id, name, amount); connection.end(); res.send({ message: 'Money sent successfully' }); }); module.exports = router;