import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { MemoryDatastoreProvider } from '@bytelyst/datastore';
import { _resetDatastoreProvider, setProvider } from '../../lib/datastore.js';
import * as repo from './repository.js';

describe('knowledge repository', () => {
  beforeEach(() => {
    setProvider(new MemoryDatastoreProvider());
  });

  afterEach(() => {
    _resetDatastoreProvider();
  });

  it('stores knowledge bases, sources, and chunks', async () => {
    await repo.createBase({
      id: 'kb_1',
      productId: 'lysnrai',
      name: 'Support KB',
      status: 'draft',
      retrievalStrategy: 'hybrid',
      tags: ['support'],
      createdBy: 'admin_1',
      createdAt: '2026-03-15T00:00:00.000Z',
      updatedAt: '2026-03-15T00:00:00.000Z',
    });

    await repo.createSource({
      id: 'ksrc_1',
      knowledgeBaseId: 'kb_1',
      productId: 'lysnrai',
      type: 'url',
      status: 'pending',
      title: 'Runbook',
      uri: 'https://example.com/runbook',
      tags: ['runbook'],
      createdAt: '2026-03-15T00:00:00.000Z',
      updatedAt: '2026-03-15T00:00:00.000Z',
    });

    await repo.upsertChunks([
      {
        id: 'kb_1:ksrc_1:0',
        knowledgeBaseId: 'kb_1',
        sourceId: 'ksrc_1',
        productId: 'lysnrai',
        ordinal: 0,
        contentText: 'Restart the worker before retrying the incident pipeline.',
        tokenCount: 11,
        embeddingStatus: 'ready',
        citations: ['https://example.com/runbook#restart'],
        tags: ['worker', 'incident'],
        createdAt: '2026-03-15T00:00:00.000Z',
      },
    ]);

    const bases = await repo.listBases('lysnrai', { limit: 20 });
    const sources = await repo.listSources('kb_1');
    const chunks = await repo.listChunks('kb_1');

    expect(bases).toHaveLength(1);
    expect(sources[0].title).toBe('Runbook');
    expect(chunks[0].embeddingStatus).toBe('ready');
  });
});
