import { createTRPCReact } from '@trpc/react-query'
import { createTRPCClient, httpBatchLink } from '@trpc/client'
import type { AppRouter } from '@backend/trpc/router'

// const BASE_API_URL = 'http://192.168.100.111:8787'
export const BASE_API_URL = 'https://worker.freshyo.in'

export const trpc = createTRPCReact<AppRouter>()

export function getTrpcClient() {
  return createTRPCClient<AppRouter>({
    links: [
      httpBatchLink({
        url: `${BASE_API_URL}/api/trpc`,
        headers: async () => {
          try {
            const token = localStorage.getItem('auth_token')
            const headers: Record<string, string> = {
              'caller-interface': 'web',
            }
            if (token) {
              headers.Authorization = `Bearer ${token}`
            }
            return headers
          } catch {}
          return { 'caller-interface': 'web' }
        },
      }),
    ],
  })
}
