import { vi } from 'vitest';
import { promises as fs } from 'fs';
import { tmpdir } from 'os';
import path from 'path';
import { setupProcessAutomation } from '../index.js';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { ConfigManager } from '../../../config/config-manager.js';

describe('Process Automation Integration Tests', () => {
  let tempDir: string;
  let mockServer: any;
  let mockConfigManager: any;
  
  beforeEach(async () => {
    // Create temp directory for tests
    tempDir = path.join(tmpdir(), `atlas-test-${Date.now()}`);
    await fs.mkdir(tempDir, { recursive: true });
    
    mockServer = {
      setRequestHandler: vi.fn()
    };
    
    mockConfigManager = {
      getDataPath: vi.fn().mockResolvedValue(tempDir),
      getModuleDataPath: vi.fn().mockReturnValue(path.join(tempDir, 'process-automation')),
      getStorageManager: vi.fn().mockReturnValue({
        getModuleDataPath: vi.fn().mockResolvedValue(path.join(tempDir, 'process-automation')),
        loadData: vi.fn().mockResolvedValue(null),
        saveData: vi.fn().mockResolvedValue(undefined),
        ensureStorageDirectories: vi.fn().mockResolvedValue(undefined)
      })
    };
  });
  
  afterEach(async () => {
    // Clean up temp directory
    try {
      await fs.rm(tempDir, { recursive: true, force: true });
    } catch (error) {
      // Ignore cleanup errors
    }
  });
  
  describe('Module Setup', () => {
    it('should setup process automation module successfully', async () => {
      const result = await setupProcessAutomation(mockServer, mockConfigManager);
      
      // The setup should complete without errors
      expect(mockServer.setRequestHandler).toHaveBeenCalled();
      
      // Verify tools are registered
      expect(mockServer.setRequestHandler).toHaveBeenCalledWith(
        expect.anything(),
        expect.any(Function)
      );
      
      // Check directories were created
      const processDir = path.join(tempDir, 'process-automation', 'processes');
      const stats = await fs.stat(processDir);
      expect(stats.isDirectory()).toBe(true);
    });
    
    it('should return expected tools configuration', async () => {
      const result = await setupProcessAutomation(mockServer, mockConfigManager);
      
      expect(result).toHaveProperty('tools');
      expect(result).toHaveProperty('resources');
      expect(result.tools).toBeInstanceOf(Array);
      
      // Check that key tools are registered
      const toolNames = result.tools.map(tool => tool.name);
      expect(toolNames).toContain('create_process');
      expect(toolNames).toContain('create_process_interactive');
      expect(toolNames).toContain('execute_process');
      expect(toolNames).toContain('suggest_triggers');
    });
  });
  
  describe('Error Handling', () => {
    it('should handle setup errors gracefully', async () => {
      // Setup should complete even with mocked components
      const result = await setupProcessAutomation(mockServer, mockConfigManager);
      
      // Should return tools and resources
      expect(result).toBeDefined();
      expect(result).toHaveProperty('tools');
      expect(result).toHaveProperty('resources');
    });
  });
});