import { dbConnection } from "db";
import type { NextApiRequest, NextApiResponse } from "next";
import {
  calculateRemainingTime,
} from "../../../../../utils/helpers";

import { gameConfig } from "@/utils/gameLogic";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  try {
    if (req.method === "POST") {
      const { userId } = req.query;
      const {
        inventoryItemId,
        wellId,
      } = req.body;
      console.log(`Start take: inventoryItemId: ${inventoryItemId} | wellId: ${wellId}`)

      const db = await dbConnection;
      try {
        const inventorySql = `
          SELECT inventory_item.id, tier, store_item_id, staking_event.id as stakeId,
                staking_event.created_at as stakeTime, duration_in_mins, stake_amount
          FROM inventory_item
          LEFT JOIN staking_event ON inventory_item_id = inventory_item.id
          WHERE inventory_item.id = ? AND inventory_item.user_id = ?
          ORDER BY staking_event.created_at;
        `;

        const invItem = await db.get(inventorySql, [inventoryItemId, userId]);

        const well = await db.get(`
          SELECT resource_well.id, resname, source_id, supply as wellId FROM resource_well
          INNER JOIN staking_source ON source_id = staking_source.id
          WHERE resource_well.id = ? AND user_id = ?;
        `, [wellId, userId]);

        if (well == undefined) {
          return res.status(400).json({error: `Well ${wellId} not found`});
        }

        const item = gameConfig.store.find((i) => i.id == invItem.store_item_id);
        if (invItem == undefined || well == undefined || item == undefined) {
          return res.status(400).json({ error: "A resource was not found" });
        }

        if (invItem.stakeId != undefined) {
          const timeRemaining = calculateRemainingTime(invItem.stakeTime, invItem.duration_in_mins);
          console.log(timeRemaining);
          if (timeRemaining > 0) {
            return res.status(400).json({error: `Item is still in use ${timeRemaining}`});
          }
        }

        const boost = invItem.tier > 0 ? item.upgrades[invItem.tier - 1].claimBoost : 0;
        const totalClaim = item.claimAmount + boost;
        console.log(userId + " " +  well.id + " " + invItem.id)
        await db.run(`INSERT INTO staking_event(user_id, well_id, inventory_item_id, duration_in_mins, stake_amount)
                      VALUES (?,?,?,?,?)`,
                     [userId, well.id, invItem.id, item.completionTimeInMins, totalClaim]);
      } catch (error) {
        if(error instanceof Error){
          return res.status(400).json({ error: error.message});
        }else {
          return res.status(400).json({ error: "Unknown Error"});
        }
      }

      return res.status(200).json({result: "Successfully started a stake"});
    }
  } catch (error) {
    if(error instanceof Error){
      res.status(500).json(error.message);
    }else {
      res.status(500).json({ error: "Unknown Error"});
    }
  }
}
