import { OpenAPI } from './api';
import { logger } from './utils/logger';

const clientLogger = logger.namespace('client');

/**
 * API 请求 Base URL（浏览器端）
 * - 不设或为空：请求走同源，由 Next rewrites 转发到 API_URL（同源、避免 CORS）
 * - 设为完整地址（如 http://localhost:8000）：直连后端
 * 服务端 rewrites 目标由 next.config 中的 API_URL 控制
 */
OpenAPI.BASE = process.env.NEXT_PUBLIC_API_URL ?? '';

clientLogger.debug('OpenAPI.BASE configured');

/**
 * Set up JWT token resolver for authenticated requests
 * This reads the access token from localStorage (zustand auth store)
 */
OpenAPI.TOKEN = async () => {
  if (typeof window === 'undefined') {
    return '';
  }
  try {
    const authStorage = localStorage.getItem('auth-storage');
    if (authStorage) {
      const parsed = JSON.parse(authStorage);
      const token = parsed?.state?.accessToken;
      return token || '';
    }
  } catch (e) {
    clientLogger.error('Error reading auth token', e);
  }
  return '';
};

// Export all services and models from the generated client
export * from './api';
