import { tap, expect } from '@push.rocks/tapbundle';
import { Qenv } from '@push.rocks/qenv';
import * as smartmongo from '@push.rocks/smartmongo';
import { smartunique } from '../ts/plugins.js';

const testQenv = new Qenv(process.cwd(), process.cwd() + '/.nogit/');

console.log(process.memoryUsage());

// the tested module
import * as smartdata from '../ts/index.js';

// =======================================
// Connecting to the database server
// =======================================

let smartmongoInstance: smartmongo.SmartMongo;
let testDb: smartdata.SmartdataDb;

tap.test('should create a testinstance as database', async () => {
  smartmongoInstance = await smartmongo.SmartMongo.createAndStart();
  testDb = new smartdata.SmartdataDb(await smartmongoInstance.getMongoDescriptor());
  await testDb.init();
});

tap.skip.test('should connect to atlas', async (tools) => {
  const databaseName = `test-smartdata-${smartunique.shortId()}`;
  testDb = new smartdata.SmartdataDb({
    mongoDbUrl: await testQenv.getEnvVarOnDemand('MONGO_URL'),
    mongoDbName: databaseName,
  });
  await testDb.init();
});

let easyStore: smartdata.EasyStore<{
  key1: string;
  key2: string;
}>;

tap.test('should create an easystore', async () => {
  easyStore = await testDb.createEasyStore('hellothere');
  await easyStore.writeKey('key1', 'hello');
  const retrievedKey = await easyStore.readKey('key1');
  expect(retrievedKey).toEqual('hello');
});

tap.test('close', async () => {
  await testDb.mongoDb.dropDatabase();
  await testDb.close();
  if (smartmongoInstance) {
    await smartmongoInstance.stop();
  }
});

tap.start();