// Backend singleton — provides a single access point for the active backend adapter.
// Set once at app startup (App.svelte), consumed by all stores and adapters.

import type { BackendAdapter } from '@agor/types';

let _adapter: BackendAdapter | null = null;

/**
 * Get the active backend adapter.
 * Throws if called before setBackend() — this is intentional to catch
 * initialization ordering bugs early.
 */
export function getBackend(): BackendAdapter {
  if (!_adapter) {
    throw new Error(
      '[backend] Adapter not initialized. Call setBackend() before accessing the backend.'
    );
  }
  return _adapter;
}

/**
 * Set the active backend adapter. Call once at app startup.
 * Calling twice throws to prevent accidental re-initialization.
 */
export function setBackend(adapter: BackendAdapter): void {
  if (_adapter) {
    throw new Error(
      '[backend] Adapter already set. setBackend() must be called exactly once.'
    );
  }
  _adapter = adapter;
}

/**
 * Replace the backend with a partial mock for testing.
 * Only available in test environments — does NOT enforce single-set.
 */
export function setBackendForTesting(adapter: Partial<BackendAdapter>): void {
  _adapter = adapter as BackendAdapter;
}

/**
 * Reset the backend to uninitialized state.
 * Only for testing — production code should never need this.
 */
export function resetBackendForTesting(): void {
  _adapter = null;
}
