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

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  try {
    if (req.method === "GET") {
      const { userId } = req.query;
      const db = await dbConnection;
      const userSql = `SELECT * FROM users WHERE id = ?`;
      const user = await db.all(userSql, [userId]);
      if (user.length === 0) return res.status(404).json("User not found");

      const resourceAccountsSql = `
        SELECT id,resname as resourceType,balance
        FROM resource_account
        WHERE user_id = ?`;
      // need resourceName or at least a way to map together with gameConfiq
      const resourceAccounts = await db.all(resourceAccountsSql, [userId]);

      const bankAccountSql = `SELECT * FROM bank_account WHERE user_id = ?`;
      const bankAccount = await db.all(bankAccountSql, [userId]);

      const bankAccountObj = {
        id: bankAccount[0].id,
        primaryBalance: bankAccount[0].balance,
        resourceAccounts: resourceAccounts,
      };

      return res.status(200).json(bankAccountObj);
    }

    if (req.method === "PUT") {
      // sell resource
      // payload userId, key:resourceName/value:amount
      const { userId } = req.query;
      const { obj } = req.body;
      // make sure they have each resource they say they have
      // calculate conversion rates
      // increment balance
      // decrement resources
    }
  } catch (error) {
    res.status(500).json(error);
  }
}
