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

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

let _provider: DatastoreProvider | null = null;

/**
 * Initialize the datastore provider.
 * Auto-initializes on first getCollection() call.
 */
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;
}

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

/**
 * Check datastore health.
 */
export async function isDatastoreHealthy(): Promise<boolean> {
  if (!_provider) initDatastore();
  return _provider!.isHealthy();
}
