import { rejectionErrorFns } from "../errors"
import type { RawToken } from "./createTokenDB"
import sendError, { API } from "./sendError"

async function getTokenFromBody<T>(context: API<T>): Promise<RawToken> {
  const type = "ACCESS"
  const body = JSON.parse(context.req.body)
  // Checking for cookie presens, because it is necessary
  if (
    typeof body === "object" &&
    body &&
    "token" in body &&
    typeof body.token === "string"
  ) {
    const value = body.token
    return { value, type }
  }
  console.log(body)

  throw sendError(context, rejectionErrorFns.noToken(type))
}

export default getTokenFromBody
