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

let provider: DatastoreProvider | null = null;

export function initDatastore(): DatastoreProvider {
  if (provider) {
    return provider;
  }

  const isTest = process.env.NODE_ENV === 'test';
  const dbProvider = (process.env.DB_PROVIDER || (isTest ? 'memory' : 'cosmos')).toLowerCase();

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

  setDatastore(provider);
  return provider;
}

export function setProvider(nextProvider: DatastoreProvider): void {
  provider = nextProvider;
  setDatastore(nextProvider);
}

export function getCollection<T extends BaseDocument = BaseDocument>(
  name: string,
  partitionKeyPath: string = '/productId'
): DocumentCollection<T> {
  if (!provider) {
    initDatastore();
  }

  return provider!.getCollection<T>(name, partitionKeyPath);
}

export function resetDatastoreProvider(): void {
  provider = null;
}
