import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import cookies from 'js-cookie';
import type { AppRouter } from '@ibcornelsen/api';
import { Buffer } from 'buffer';

let url: string = 'http://localhost:3001/';

if (typeof window !== "undefined" && window.location.hostname !== "localhost") {
	url = "http://rpc.ibcornelsen.de/"
}


export const client = createTRPCProxyClient<AppRouter>({
  links: [
    httpBatchLink({
      url,
      headers() {
				const accessToken = cookies.get('accessToken');
				if (!accessToken) return {};

				const buffer = Buffer.from(accessToken, 'utf-8');
				const base64 = buffer.toString('base64')

        return {
          'Authorization': `Bearer ${base64}`,
        };
      },
    }),
  ],
});