"use client"

import { TRPCClientError } from "@trpc/client"

import { login } from "@scandic-hotels/common/constants/routes/handleAuth"
import { logger } from "@scandic-hotels/common/logger"
import { SessionExpiredError } from "@scandic-hotels/trpc/errors"
import { TrpcProvider as InternalTrpcProvider } from "@scandic-hotels/trpc/Provider"

import useLang from "@/hooks/useLang"

import type { AnyTRPCRouter } from "@trpc/server"

export default function TrpcProvider({
  children,
}: {
  children: React.ReactNode
}) {
  const lang = useLang()

  return (
    <InternalTrpcProvider
      onError={(error) => {
        if (error instanceof TRPCClientError) {
          const appError: TRPCClientError<AnyTRPCRouter> = error
          logger.error("trpc error", { appError })
          if (appError.data?.code === "UNAUTHORIZED") {
            if (appError.data?.cause instanceof SessionExpiredError) {
              // TODO verify login url
              const loginUrl = login[lang]
              window.location.assign(loginUrl)
            }
          }
        }
      }}
    >
      {children}
    </InternalTrpcProvider>
  )
}
