import { createTRPCClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from '../../../server/trpc';

let cachedToken: string | null = null;

function getAuthToken(): string | null {
  if (typeof window === 'undefined') return null;
  if (cachedToken) return cachedToken;
  cachedToken = localStorage.getItem('auth_token');
  return cachedToken;
}

export function setAuthToken(token: string | null) {
  cachedToken = token;
  if (typeof window !== 'undefined') {
    if (token) {
      localStorage.setItem('auth_token', token);
    } else {
      localStorage.removeItem('auth_token');
    }
  }
}

// Create tRPC client with auth
export const trpc = createTRPCClient<AppRouter>({
  links: [
    httpBatchLink({
      url: `${(import.meta as any).env?.VITE_API_URL || 'http://localhost:8080'}/trpc`,
      headers: () => {
        const token = getAuthToken();
        return {
          authorization: token ? `Bearer ${token}` : '',
        };
      },
    }),
  ],
});

export type { AppRouter };
