/**
 * Test helpers for @bytelyst/datastore.
 *
 * Use setTestProvider('memory') in beforeAll() to wire up
 * a fast, deterministic in-memory provider for tests.
 */

import { setDatastore, _resetDatastore } from './factory.js';
import { MemoryDatastoreProvider } from './providers/memory.js';
import type { BaseDocument, DocumentCollection, DatastoreProviderType } from './types.js';

let _testProvider: MemoryDatastoreProvider | null = null;

/**
 * Set a test provider. Call in beforeAll().
 * Currently only 'memory' is supported for testing.
 */
export function setTestProvider(type: DatastoreProviderType = 'memory'): MemoryDatastoreProvider {
  if (type !== 'memory') {
    throw new Error(`setTestProvider only supports 'memory', got '${type}'`);
  }
  _testProvider = new MemoryDatastoreProvider();
  setDatastore(_testProvider);
  return _testProvider;
}

/**
 * Clear all test data. Call in afterEach() or afterAll().
 */
export function clearTestData(): void {
  _testProvider?.clear();
}

/**
 * Reset the test provider. Call in afterAll().
 */
export function resetTestProvider(): void {
  _testProvider?.clear();
  _testProvider = null;
  _resetDatastore();
}

/**
 * Seed a collection with documents for testing.
 */
export async function seedCollection<T extends BaseDocument>(
  collection: DocumentCollection<T>,
  docs: T[]
): Promise<void> {
  for (const doc of docs) {
    await collection.create(doc);
  }
}
