import { dbConnection } from "db";
import type { NextApiRequest, NextApiResponse } from "next";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  // http://127.0.0.1:3000/api/user/1/add-balance/100
  // Remember to change to POST
  try {
    if (req.method === "GET") {
      const { userId, amount } = req.query;
      const db = await dbConnection;
      const sql = `
        UPDATE bank_account SET balance = balance + ?
        WHERE user_id = ?`;
      const result = await db.run(sql, [amount, userId])
      if (result.changes == 0) {
        return res.status(400).json({error: `User ${userId} was not found`});
      } else {
        return res.status(200).json({message: result});
      }
    }
  } catch (error) {
    return res.status(500).json(error);
  }
}
