import { dbConnection } from "db";
import type { NextApiRequest, NextApiResponse } from "next";
import { IInventoryItem } from "typings";
import { updateAllToCamelCase } from "@/utils/helpers";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  try {
    if (req.method === "GET") {
      const { userId } = req.query;
      const db = await dbConnection;
      // This is supposed to be activeStakes?
      const inventorySql = `
          SELECT staking_event.id, staking_source.id as sourceId, resname as resourceType,
                 inventory_item_id, duration_in_mins, stake_amount, staking_event.created_at,
                 CASE WHEN claim_event.staking_event_id IS NULL THEN 1 ELSE 0 END AS unclaimed
          FROM staking_event
          INNER JOIN resource_well ON well_id = resource_well.id
          INNER JOIN staking_source ON source_id = staking_source.id
          LEFT JOIN claim_event ON staking_event.id = claim_event.staking_event_id
          WHERE staking_event.user_id = ?`;
      const inventoryItems = await db.all(inventorySql, [userId]);

      // Change all keys to camelCase
      // const updatedInventoryItems = updateAllToCamelCase(inventoryItems)

      return res.status(200).json(inventoryItems);
    }
  } catch (error) {
    res.status(500).json(error);
  }
}
