import { TRPCError } from "@trpc/server"
import { redirect } from "next/navigation"

import { Lang } from "@/constants/languages"
import { webviews } from "@/constants/routes/webviews"
import { appRouter } from "@/server"
import { createContext } from "@/server/context"
import { internalServerError } from "@/server/errors/next"
import { createCallerFactory } from "@/server/trpc"

const createCaller = createCallerFactory(appRouter)

export function serverClient() {
  return createCaller(createContext(), {
    onError: ({ ctx, error, input, path, type }) => {
      console.error(`Server Client error for ${type}: ${path}`)
      if (input) {
        console.error(`Received input:`)
        console.error(input)
      }
      console.error(error)

      if (error instanceof TRPCError) {
        if (error.code === "UNAUTHORIZED") {
          let lang = Lang.en
          let pathname = "/"
          let fullUrl = "/"

          if (ctx) {
            lang = ctx.lang
            pathname = ctx.pathname
            fullUrl = ctx.url
          }

          const fullPathname = new URL(fullUrl).pathname

          if (webviews.includes(fullPathname)) {
            const redirectUrl = `/${lang}/webview/refresh?returnurl=${encodeURIComponent(fullPathname)}`
            console.error(
              "Unautorized in webview, redirecting to: ",
              redirectUrl
            )

            redirect(redirectUrl)
          }

          redirect(
            `/${lang}/login?redirectTo=${encodeURIComponent(`/${lang}/${pathname}`)}`
          )
        }
      }

      throw internalServerError()
    },
  })
}
