import { postgresConnection } from "db";
import type { NextApiRequest, NextApiResponse } from "next";
import { gameConfig } from "@/utils/gameLogic";

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

      // TODO: We probably shouldn't keep the tier as a column in the database, we can
      // just do a join and count how many upgrades there are
      const inventorySql = `
        SELECT id, store_item_id as "storeItemId", tier as "currentTierIndex"
        FROM inventory_item WHERE user_id = $1`;
      const results = await db.query(inventorySql, [userId]);

      return res.status(200).json({"inventoryItems": results.rows});

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

      // Buy a new item
      const { userId } = req.query;
      const { storeItemId } = req.body;

      // TODO: Split the try catch to report already owned item error
      try {
        const result = await db.query("select purchase_item($1, $2)", [userId, storeItemId]);
        return res.status(200).json({ "newItemId": result.rows[0].purchase_item});
      } catch (error) {
        // TODO: Need to add better error handling when the user dodn't have enough money
        return res.status(400).json({ error: error.message});
      }

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

      // Upgrade an existing item
      const { userId } = req.query;
      const { inventoryItemId } = req.body;

      try {
        const result = await db.query("SELECT upgrade_item($1, $2)", [userId, inventoryItemId]);
        return res.status(200).json({ message: `Upgraded item ${inventoryItemId}`,
                                      upgradeEventId: result.rows[0].upgrade_item});
      } catch (error) {
        return res.status(400).json({ error: error.message});
      }
    }
  } catch (error) {
    if(error instanceof Error){
      res.status(500).json(error.message);
    }else {
      res.status(500).json("Unknow Error");
    }
  }
}
