"use client"

import { redirect } from "next/navigation"
import { useSession } from "next-auth/react"

import { logoutSafely } from "@scandic-hotels/common/constants/routes/handleAuth"
import { trpc } from "@scandic-hotels/trpc/client"

import { userNotFound } from "@/constants/routes/errorPages"

import useLang from "@/hooks/useLang"
import { isValidClientSession } from "@/utils/clientSession"

export function UserExists() {
  const { data: session } = useSession()
  const isUserLoggedIn = isValidClientSession(session)
  const lang = useLang()

  const { isLoading: isLoadingUser, error } = trpc.user.get.useQuery(
    undefined,
    {
      enabled: isUserLoggedIn,
    }
  )

  if (!isUserLoggedIn) {
    return null
  }

  if (isLoadingUser) {
    return null
  }

  switch (error?.data?.code) {
    case "NOT_FOUND":
      redirect(
        `${logoutSafely[lang]}?redirectTo=${encodeURIComponent(userNotFound[lang])}`
      )
    default:
      return null
  }
}
