import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { getSQLiteManager } from '../../../storage/sqlite-manager.js';
import { setupMemoryManagementTools } from '../tools.js';

describe('Memory Management Integration Tests - Real SQLite', () => {
  let db: any;
  let tools: any;

  beforeEach(async () => {
    // Create a unique database for each test
    const testDbPath = `.atlas/test-memory-${Date.now()}.db`;
    
    const { createSQLiteManager } = await import('../../../storage/sqlite-manager.js');
    db = createSQLiteManager(testDbPath);
    
    // Initialize the database
    await db.initialize();
    
    // Create a test project to satisfy foreign key constraint
    await db.run(
      'INSERT INTO projects (id, name, description, created_at, updated_at) VALUES (?, ?, ?, ?, ?)',
      ['test-project', 'Test Project', 'Project for testing', Date.now(), Date.now()]
    );
    
    // Setup tools
    const toolRegistration = await setupMemoryManagementTools();
    tools = {};
    for (const tool of toolRegistration.tools) {
      tools[tool.name] = tool;
    }
  });

  afterEach(async () => {
    if (db) {
      await db.close();
    }
  });

  const createContext = (toolName: string) => ({
    toolName,
    requestId: 'test-req-1',
    projectId: 'test-project',
    userId: 'test-user',
    timestamp: Date.now(),
    db
  });

  it('should successfully store memory with all new columns', async () => {
    const input = {
      content: 'Test memory after schema fix - this should work now',
      type: 'learning' as const,
      title: 'Schema Fix Test',
      tags: ['test', 'schema', 'fix'],
      importance: 'high' as const,
      category: 'testing',
      source: 'manual_test'
    };

    const result = await tools.store_memory.execute(input, createContext('store_memory'));

    expect(result.success).toBe(true);
    expect(result.data).toBeDefined();
    expect(result.data.memory).toBeDefined();
    expect(result.data.memory.title).toBe('Schema Fix Test');
    expect(result.data.memory.tags).toEqual(['test', 'schema', 'fix']);
    expect(result.data.memory.importance).toBe('high');
    expect(result.data.memory.category).toBe('testing');
    expect(result.data.memory.type).toBe('learning');
    expect(result.data.memory.id).toBeDefined();
  });

  it('should verify memory was actually stored in database', async () => {
    const input = {
      content: 'Database verification test',
      type: 'context' as const,
      title: 'DB Verification',
      tags: ['database', 'verification'],
      importance: 'medium' as const,
      category: 'testing'
    };

    // Store the memory
    await tools.store_memory.execute(input, createContext('store_memory'));

    // Query the database directly to verify
    const queryResult = await db.query(
      'SELECT * FROM memories WHERE title = ?',
      ['DB Verification']
    );

    expect(queryResult.success).toBe(true);
    expect(queryResult.data).toHaveLength(1);
    
    const memory = queryResult.data[0];
    expect(memory.title).toBe('DB Verification');
    expect(memory.content).toBe('Database verification test');
    expect(JSON.parse(memory.tags)).toEqual(['database', 'verification']);
    expect(memory.importance).toBe('medium');
    expect(memory.category).toBe('testing');
  });

  it('should handle memory with minimal fields', async () => {
    const input = {
      content: 'Minimal memory test',
      type: 'insight' as const,
      title: 'Minimal Test'
    };

    const result = await tools.store_memory.execute(input, createContext('store_memory'));

    expect(result.success).toBe(true);
    expect(result.data.memory.title).toBe('Minimal Test');
    expect(result.data.memory.type).toBe('insight');
    expect(result.data.memory.tags).toEqual([]);
    expect(result.data.memory.importance).toBe('medium'); // default
  });

  it('should search memories by title', async () => {
    // Store multiple memories
    await tools.store_memory.execute({
      content: 'First memory',
      type: 'documentation' as const,
      title: 'Search Test 1',
      tags: ['search']
    }, createContext('store_memory'));

    await tools.store_memory.execute({
      content: 'Second memory',
      type: 'documentation' as const,
      title: 'Search Test 2',
      tags: ['search']
    }, createContext('store_memory'));

    // Search for memories
    const searchResult = await tools.search_memory.execute({
      query: 'Search Test',
      limit: 10
    }, createContext('search_memory'));

    expect(searchResult.success).toBe(true);
    expect(searchResult.data.memories).toHaveLength(2);
    expect(searchResult.data.memories.some(m => m.title === 'Search Test 1')).toBe(true);
    expect(searchResult.data.memories.some(m => m.title === 'Search Test 2')).toBe(true);
  });
});