import { postgresConnection } from "db";
import type { NextApiRequest, NextApiResponse } from "next";
import { IStakingSource } from "typings";
import { gameConfig } from "@/utils/gameLogic";
import {
  generateRandomBase64String,
} from "../../../../utils/helpers";

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

      const results = await db.query({ text: "SELECT * from get_staking_sources($1)",
                                       values: [userId], rowMode: 'array' });
      
      // TODO: Do it this way until we get an ORM working, I guess
      const stakingSources: IStakingSource[] = results.rows.map(row => {
        return {
          id: row[0],
          name: row[1],
          description: row[2],
          image: row[3],
          resourceWells: row[4],
          activeStakes: row[5]
        };
      });
      return res.status(200).json({ "stakingSources": stakingSources });
    } else if (req.method === "POST") {

      const { userId } = req.query;

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

        if (result.rows.length > 0) {
          return res.status(200).json({"stakingSourceId": result.rows[0].create_staking_source});
        } else {
          return res.status(400).json({"error": "Something happened and I don't know what"});
        }
      } catch (error) {
        // TODO: Have to change this to match postgres' error or figure out a way to explicitly
        // return this message from the postgres function
        if (error.message.includes("CHECK constraint failed")) {
          return res.status(400).json({ "error": "Insuficcient funds" });
        } else {
          return res.status(400).json({ "error": error.message });
        }
      }
    }
  } catch (error) {
    res.status(500).json(error.message);
  }
}
