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

export const trpc = createTRPCReact<AppRouter>()



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}` } : {};
        },
        fetch(url, options) {
          return fetch(url, {
            ...options,
            credentials: 'include'
          })
        }
      })
    ]
  })
}
