/**
 * Cloud-agnostic datastore bridge for platform-service.
 *
 * Wraps @bytelyst/datastore with platform-service container registry config.
 * Repositories import getCollection() from here instead of getContainer() from cosmos.
 *
 * Migration: Replace `import { getContainer } from '../../lib/cosmos.js'`
 *       with `import { getCollection } from '../../lib/datastore.js'`
 */

import {
  type DatastoreProvider,
  type DocumentCollection,
  type BaseDocument,
  setDatastore,
  CosmosDatastoreProvider,
  MemoryDatastoreProvider,
} from '@bytelyst/datastore';

let _provider: DatastoreProvider | null = null;

/**
 * Initialize the datastore provider.
 * Call once at service startup (before any repository calls).
 */
export function initDatastore(): DatastoreProvider {
  if (_provider) return _provider;

  const dbProvider = (process.env.DB_PROVIDER || 'cosmos').toLowerCase();

  if (dbProvider === 'memory') {
    _provider = new MemoryDatastoreProvider();
  } else {
    _provider = new CosmosDatastoreProvider();
  }

  setDatastore(_provider);
  return _provider;
}

/**
 * Inject a provider directly (for testing).
 */
export function setProvider(provider: DatastoreProvider): void {
  _provider = provider;
}

/**
 * Get a typed collection from the datastore.
 * Drop-in replacement for getContainer() — returns a DocumentCollection instead of a Cosmos Container.
 */
export function getCollection<T extends BaseDocument = BaseDocument>(
  name: string,
  partitionKeyPath: string = '/productId'
): DocumentCollection<T> {
  if (!_provider) {
    initDatastore();
  }
  return _provider!.getCollection<T>(name, partitionKeyPath);
}

/**
 * @internal — for testing only
 */
export function _resetDatastoreProvider(): void {
  _provider = null;
}
