import { NextApiRequest, NextApiResponse } from "next"
import prisma from "../../prisma"

async function getTokenDB<T>(
  payload: T & {
    tokenBody: string
    tokenIsValid: boolean
    req: NextApiRequest
    res: NextApiResponse<any>
  }
) {
  const { tokenBody } = payload

  // Find refresh token in DB
  const tokenDB = await prisma.token.findUnique({
    where: {
      token: tokenBody,
    },
  })
  if (!tokenDB) {
    return Promise.reject({
      message: "Access-Token not found in DB!",
      statusCode: 401,
      solved: true,
      type: "warn",
    })
  }

  if (tokenDB.used) {
    return Promise.reject({
      message: "DBToken was already used!",
      statusCode: 401,
      solved: true,
    })
  }

  await prisma.token.update({
    where: {
      token: tokenBody,
    },
    data: {
      used: true,
    },
  })

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

  return {
    ...payload,
    tokenDB,
  }
}

export default getTokenDB
