import prisma from "../../prisma"
import { rejectionErrorFns, rejectionErrors } from "../errors"
import type { IdToken } from "./createTokenDB"
import sendError, { API } from "./sendError"
import { deleteCookie } from "cookies-next"

async function getTokenDB<T>(
  context: API<T>,
  token: IdToken,

  ignoreChecks?: boolean
) {
  const { id, type } = token
  // Find refresh token in DB
  const tokenDB = await prisma.token.findUnique({
    where: {
      id,
    },
  })
  if (!tokenDB) {
    deleteCookie("token", { ...context, path: "/api" })
    throw sendError(context, rejectionErrorFns.tokenNotFound(type))
  }

  if (tokenDB.used && !ignoreChecks)
    throw sendError(context, rejectionErrors.tokenUsed)

  await prisma.token.update({
    where: {
      id,
    },
    data: {
      used: type === "ACCESS",
    },
  })

  // await logging('Old token has been invalidated.', ['debug'], req)

  return tokenDB
}

export default getTokenDB
