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

import { Lang } from "@/constants/languages"
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") {
          const lang = ctx?.lang || Lang.en
          const pathname = ctx?.pathname || "/"
          redirect(
            `/${lang}/login?redirectTo=${encodeURIComponent(`/${lang}/${pathname}`)}`
          )
        }
      }

      throw internalServerError()
    },
  })
}
