import type { Router } from "./router";
import { createTRPCProxyClient, httpBatchLink } from "@trpc/client";

import type { QueryClient } from "@tanstack/svelte-query";
import { svelteQueryWrapper } from "trpc-svelte-query-adapter";
import { createTRPCClient, type TRPCClientInit } from "trpc-sveltekit";
import { PUBLIC_SITE_URL } from "$lib/core/constants";

const client = createTRPCProxyClient<Router>({
	links: [httpBatchLink({ url: PUBLIC_SITE_URL + "/trpc/" })],
});

let browserClient: ReturnType<typeof createTRPCClient<Router>>;

export function trpcRaw(init?: TRPCClientInit) {
	const isBrowser = typeof window !== "undefined";
	if (isBrowser && browserClient) return browserClient;
	const client = createTRPCClient<Router>({ init });
	if (isBrowser) browserClient = client;
	return client;
}

export type TRPC_RAW = ReturnType<typeof trpcRaw>;

export function trpc(queryClient?: QueryClient) {
	return svelteQueryWrapper<Router>({ client, queryClient });
}

export type TRPC = ReturnType<typeof trpc>;
