import { createTRPCReact } from '@trpc/react-query'
import { httpBatchLink, loggerLink } from '@trpc/client'
import type { AppRouter as MyRouter } from '../../../backend/src/trpc/router'
import webUiConstants from '@/constants'
import { getAuthToken } from '@/services/auth'
import { redirectToLogin } from '@/lib/auth-redirect'

// export const trpc = createTRPCReact<AppRouter>()
export const trpc = createTRPCReact<MyRouter>()



export function createTRPCClient() {
  return trpc.createClient({
    // transformer: superjson,
    links: [
      loggerLink({
        enabled: (opts) =>
          import.meta.env.DEV ||
          (opts.direction === 'down' && opts.result instanceof Error)
      }),
      httpBatchLink({
        url: webUiConstants.baseUrl+`api/trpc`,
        headers: async () => {
          const token = await getAuthToken();
          return token ? { Authorization: `Bearer ${token}` } : {};
        },
        async fetch(url, options) {
          const response = await fetch(url, {
            ...options,
            credentials: 'include'
          })

          if (response.status === 401) {
            redirectToLogin()
          }

          return response
        }
      })
    ]
  })
}
