interface AppConfig {
  logtoEndpoint: string;
  logtoClientId: string;
  logtoResource: string;
  scopes: string[];
}

let cached: AppConfig | null = null;

export async function fetchConfig(): Promise<AppConfig> {
  if (cached) return cached;

  try {
    const response = await fetch('/platform/api/config');
    if (response.ok) {
      cached = await response.json();
      return cached!;
    }
  } catch {
    // Config endpoint not available (e.g., Vite dev without backend)
  }

  // Fallback to env vars (Vite dev mode)
  cached = {
    logtoEndpoint: import.meta.env.VITE_LOGTO_ENDPOINT || window.location.origin,
    logtoClientId: import.meta.env.VITE_LOGTO_CLIENT_ID || '',
    logtoResource: import.meta.env.VITE_LOGTO_RESOURCE || '',
    scopes: [
      'platform:admin',
      'tenant:manage',
      'billing:manage',
      'team:manage',
      'apps:manage',
      'apps:deploy',
      'secrets:manage',
      'observe:read',
      'observe:debug',
      'settings:manage',
    ],
  };
  return cached;
}
