import { assertEquals, assertExists } from 'https://deno.land/std@0.208.0/assert/mod.ts';
import { LocalTsmDb } from '@push.rocks/smartmongo';
import { SmartdataDb, SmartDataDbDoc, Collection, svDb, unI } from '@push.rocks/smartdata';

Deno.test({
  name: 'TsmDb spike: LocalTsmDb + SmartdataDb roundtrip',
  sanitizeOps: false,
  sanitizeResources: false,
  fn: async () => {
    const tmpDir = await Deno.makeTempDir();

    // 1. Start local MongoDB-compatible server
    const localDb = new LocalTsmDb({ folderPath: tmpDir });
    const { connectionUri } = await localDb.start();
    assertExists(connectionUri);

    // 2. Connect smartdata
    const smartDb = new SmartdataDb({
      mongoDbUrl: connectionUri,
      mongoDbName: 'gitops_spike_test',
    });
    await smartDb.init();
    assertEquals(smartDb.status, 'connected');

    // 3. Define a simple document class
    @Collection(() => smartDb)
    class TestDoc extends SmartDataDbDoc<TestDoc, TestDoc> {
      @unI()
      public id: string = '';

      @svDb()
      public label: string = '';

      @svDb()
      public value: number = 0;

      constructor() {
        super();
      }
    }

    // 4. Insert a document
    const doc = new TestDoc();
    doc.id = 'test-1';
    doc.label = 'spike';
    doc.value = 42;
    await doc.save();

    // 5. Query it back
    const found = await TestDoc.getInstance({ id: 'test-1' });
    assertExists(found);
    assertEquals(found.label, 'spike');
    assertEquals(found.value, 42);

    // 6. Cleanup — smartDb closes; localDb.stop() hangs under Deno, so fire-and-forget
    await smartDb.close();
    localDb.stop().catch(() => {});
  },
});
