import { postgresConnection } from "db";
import type { NextApiRequest, NextApiResponse } from "next";
import { checkIfValidUUID } from "@/utils/helpers";
import { IBankAccount } from "typings";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  try {
    if (req.method === "GET") {
      const { userId } = req.query;
      const db = postgresConnection;

      if (!checkIfValidUUID(userId)) {
        return res.status(400).json({error: "Invalid UUID for user id"});
      }

      const result = await db.query("SELECT * FROM get_accounts($1)", [userId]);

      if (result.rowCount > 0) {
        return res.status(200).json(result.rows[0]);
      } else {
        return res.status(400).json({error: "Could not find accounts for user"});
      }
    }

    if (req.method === "PUT") {
      // sell resource
      // payload userId, key:resourceName/value:amount
      const { userId } = req.query;
      // an array of IConversionPairs
      const { pairs } = req.body;
      // check they have appropriate amount of each resource
      // increment balance
      // decrement resources
    }
  } catch (error) {
    res.status(500).json(error);
  }
}
