"use client"

import { TRPCClientError } from "@trpc/client"

import { SessionExpiredError } from "@scandic-hotels/trpc/errors"
import { TrpcProvider as InternalTrpcProvider } from "@scandic-hotels/trpc/Provider"

import { login } from "@/constants/routes/handleAuth"

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
          console.log({ appError })
          if (appError.data?.code === "UNAUTHORIZED") {
            if (appError.data?.cause instanceof SessionExpiredError) {
              const loginUrl = login[lang]
              window.location.assign(loginUrl)
            }
          }
        }
      }}
    >
      {children}
    </InternalTrpcProvider>
  )
}
