"use client";

import { createTRPCReact } from "@trpc/react-query";
import { createWSClient, httpBatchLink, splitLink, wsLink } from "@trpc/client";
import { appRouter } from "@lifetracker/trpc/routers/_app";
import SuperJSON from "superjson";

export const api = createTRPCReact<typeof appRouter>();

const wsClient = createWSClient({
    url: process.env.NEXT_PUBLIC_WS_URL || 'ws://localhost:3000/api/ws',
});

export const trpcClient = api.createClient({
    links: [
        splitLink({
            condition: (op) => op.type === 'subscription',
            true: httpBatchLink({
                url: '/api/ws',
                transformer: SuperJSON,
            }),
            false: wsLink({ client: wsClient, transformer: SuperJSON }),
        }),
    ],
});
