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 {
    const db = postgresConnection;
    if (req.method === "GET") {
      const { userId } = req.query;

      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"});
      }

    } else if (req.method === "PUT") {

      const { userId } = req.query;
      const { pairs } = req.body;

      const result = await db.query("select * from sell_resources($1, $2)", [userId, JSON.stringify(pairs)]);
      if (result.rowCount > 0) {
        return res.status(200).json(result.rows);
      } else {
        return res.status(400).json({error: "Could not find accounts for user"});
      }

    }
  } catch (error) {
    res.status(500).json(error.message);
  }
}
