import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import { createTRPCNext } from '@trpc/next';
import getUrls from 'config/urls';
import SuperJSON from 'superjson';
import { isServer } from 'tools/common';
import type { AppRouter } from './routers';

const { BASE_PATH, PORT } = getUrls();

function getBaseUrl() {
  if (!isServer()) return BASE_PATH;

  return `http://localhost:${PORT ?? 3000}${BASE_PATH}`;
}

const url = `${getBaseUrl()}/api/trpc`;

export const trpcClient = createTRPCNext<AppRouter>({
  config() {
    return {
      links: [
        httpBatchLink({
          url,
        }),
      ],
      transformer: SuperJSON,
    };
  },
  ssr: true,
});

export const trpcPureClient = createTRPCProxyClient<AppRouter>({
  links: [
    httpBatchLink({
      url,
    }),
  ],
  transformer: SuperJSON,
});
