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

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

      const db = await dbConnection;
      try {
        const stake = await db.get("SELECT * FROM staking_event WHERE id = ? AND user_id = ?",
                                   [stakingEventId, userId]);

        if (stake == undefined) {
          return res.status(400).json({error: "Could not find stake"});
        }

        const claim = await db.get("SELECT id FROM claim_event WHERE staking_event_id = ?",
                                   [stakingEventId])
        if (claim != undefined) {
          return res.status(400).json({error: "Stake already claimed"});
        }

        const timeRemaining = calculateRemainingTime(stake.created_at, stake.duration_in_mins);
        if (timeRemaining > 0) {
          return res.status(400).json({error: "Staking period has not ended"});
        }
        const well = await db.get("SELECT id,resname,supply FROM resource_well WHERE id = ?",
                                  [stake.well_id])

        const claimAmount = stake.stake_amount > well.supply ? well.supply : stake.stake_amount;

        await db.run("BEGIN");
        await db.run("INSERT INTO claim_event(staking_event_id, claim_amount) VALUES (?, ?)",
                     [stake.id, claimAmount])
        console.log(well.id);
        const r1 = await db.run(`UPDATE resource_well SET supply = supply - ? WHERE id = ?`,
                     [claimAmount, well.id]);
        console.log(stake.user_id, well.resname);
        const r2 = await db.run(`UPDATE resource_account SET balance = balance + ?
                      WHERE user_id = ? AND resname = ?`, [claimAmount, stake.user_id, well.resname]);
        await db.run("COMMIT");
      } catch (error) {
        await db.exec("ROLLBACK");
        return res.status(400).json({ error: error.message});
      }
      return res.status(200).json({result: "Successfully claimed stake"});
    }
  } catch (error) {
    res.status(500).json(error);
  }
}
