import { describe, it, expect, afterEach } from 'vitest';
import Database from 'better-sqlite3';
import { runMigrations } from '../db/migrate.js';
import { createToolCache } from './tool-cache.js';

describe('toolCache.replaceForServer', () => {
  let db: Database.Database;
  afterEach(() => db?.close());

  function makeDb(): Database.Database {
    db = new Database(':memory:');
    db.exec(`CREATE TABLE users (id TEXT PRIMARY KEY);`);
    db.exec(`CREATE TABLE jobs (id TEXT PRIMARY KEY, wait_reason TEXT);`);
    db.exec(`CREATE TABLE local_tasks (id INTEGER PRIMARY KEY AUTOINCREMENT);`);
    runMigrations(db);
    return db;
  }

  it('keeps camelCase tool names (NocoDB regression: previously only "aggregate" survived)', () => {
    const cache = createToolCache(makeDb(), 600);
    cache.replaceForServer('nocodb', [
      { name: 'getTablesList' },
      { name: 'queryRecords' },
      { name: 'createRecords' },
      { name: 'updateRecords' },
      { name: 'deleteRecords' },
      { name: 'aggregate' },
    ]);
    const names = cache.getForServer('nocodb').map((t) => t.toolName).sort();
    expect(names).toEqual([
      'aggregate', 'createRecords', 'deleteRecords', 'getTablesList', 'queryRecords', 'updateRecords',
    ]);
  });

  it('still skips names with illegal characters', () => {
    const cache = createToolCache(makeDb(), 600);
    cache.replaceForServer('s', [{ name: 'ok_Tool-1' }, { name: 'bad name!' }, { name: 'has.dot' }]);
    const names = cache.getForServer('s').map((t) => t.toolName);
    expect(names).toEqual(['ok_Tool-1']);
  });
});
