import status from "http-status"
import { toast } from "react-toastify"
import { ZodError, z } from "zod"

const tokenSchema = z.object({
  token: z.string(),
})

export function successfulResponse(res: Response) {
  if (status[`${res.status}_CLASS`] === status.classes.SUCCESSFUL)
    return res.json()

  const resStatus = status[`${res.status}_CLASS`]
  if (typeof resStatus !== "string") return

  toast(status.classes[resStatus] + ": " + status[res.status], {
    position: "top-center",
    type: "error",
    theme: "colored",
  })
  return Promise.reject()
}

async function getAccessToken() {
  return fetch("/api/user/auth", {
    method: "GET",
  })
    .then(successfulResponse)
    .then((response) => {
      try {
        const { token } = tokenSchema.parse(response)

        return token
      } catch (err: any) {
        const error = err as ZodError
        toast(JSON.stringify(error))
        return Promise.reject()
      }
    })
}

export default getAccessToken
