/**
 * Datastore provider factory.
 *
 * Creates a DatastoreProvider based on DB_PROVIDER env var or explicit type.
 * Defaults to 'cosmos' for backward compatibility.
 */

import { MemoryDatastoreProvider } from './providers/memory.js';
import type { DatastoreProvider, DatastoreProviderType } from './types.js';

let _provider: DatastoreProvider | null = null;

/**
 * Get the singleton datastore provider.
 * Lazily creates on first call based on DB_PROVIDER env var.
 *
 * - 'cosmos' (default) — Azure Cosmos DB
 * - 'memory' — In-memory (for testing)
 */
export async function getDatastore(): Promise<DatastoreProvider> {
  if (!_provider) {
    const providerType = (process.env.DB_PROVIDER || 'cosmos') as DatastoreProviderType;
    _provider = await createDatastoreProvider(providerType);
  }
  return _provider;
}

/**
 * Create a datastore provider by type.
 */
export async function createDatastoreProvider(
  type: DatastoreProviderType
): Promise<DatastoreProvider> {
  switch (type) {
    case 'cosmos': {
      const { CosmosDatastoreProvider } = await import('./providers/cosmos.js');
      return new CosmosDatastoreProvider();
    }
    case 'memory':
      return new MemoryDatastoreProvider();
    default:
      throw new Error(`Unknown DB_PROVIDER: '${type}'. Valid: cosmos, memory`);
  }
}

/**
 * Set the singleton datastore provider directly (for testing or manual wiring).
 */
export function setDatastore(provider: DatastoreProvider): void {
  _provider = provider;
}

/**
 * Reset the singleton (for testing).
 * @internal
 */
export function _resetDatastore(): void {
  _provider = null;
}
