/**
 * better-auth клиент для web-svc
 * /api/auth проксируется через api-gateway в auth-svc
 * Bearer token (set-auth-token) сохраняется в localStorage для library-svc, memory-svc и др.
 */
import { createAuthClient } from 'better-auth/react';

const baseURL =
  typeof window !== 'undefined' ? window.location.origin : 'http://localhost:3000';

const AUTH_TOKEN_KEY = 'auth_token';

export const authClient = createAuthClient({
  baseURL,
  fetchOptions: {
    onSuccess: (ctx) => {
      const token = ctx.response?.headers?.get?.('set-auth-token');
      if (token) {
        if (typeof window !== 'undefined') {
          localStorage.setItem(AUTH_TOKEN_KEY, token);
        }
      }
    },
  },
});

export function getStoredAuthToken(): string | null {
  if (typeof window === 'undefined') return null;
  return localStorage.getItem(AUTH_TOKEN_KEY);
}

export function clearStoredAuthToken(): void {
  if (typeof window === 'undefined') return;
  localStorage.removeItem(AUTH_TOKEN_KEY);
  localStorage.removeItem('access_token');
}
