import { vi } from 'vitest';
import { promises as fs } from 'fs';
import { tmpdir } from 'os';
import path from 'path';
import { processAutomationModule } from '../index.js';
import { setupProcessAutomationTools } from '../tools.js';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';

describe('Process Automation Integration Tests', () => {
  let tempDir: string;
  let mockServer: 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()
    };
  });
  
  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 context = { server: mockServer };
      const result = await processAutomationModule.setup(context);
      
      // The setup should complete without errors
      expect(result.success).toBe(true);
      expect(result.error).toBeUndefined();
      
      // Verify tool handler was registered
      expect(mockServer.setRequestHandler).toHaveBeenCalled();
    });
    
    it('should return expected tools configuration', async () => {
      const toolRegistration = await setupProcessAutomationTools();
      
      expect(toolRegistration).toHaveProperty('tools');
      expect(toolRegistration.tools).toBeInstanceOf(Array);
      expect(toolRegistration.module).toBe('process-automation');
      
      // Check that key tools are registered
      const toolNames = toolRegistration.tools.map(tool => tool.name);
      expect(toolNames).toContain('create_process');
      expect(toolNames).toContain('execute_process');
      expect(toolNames).toContain('list_processes');
      expect(toolNames).toContain('suggest_triggers');
      expect(toolNames).toContain('process_list_templates');
    });
  });
  
  describe('Error Handling', () => {
    it('should handle setup errors gracefully', async () => {
      // Test with mock server that has no setRequestHandler
      const brokenServer = {};
      const context = { server: brokenServer };
      
      // Should handle the error gracefully (not throw)
      try {
        const result = await processAutomationModule.setup(context);
        // Either succeeds or returns error info
        expect(result).toBeDefined();
        expect(typeof result.success).toBe('boolean');
      } catch (error) {
        // If it throws, that's also acceptable for this test
        expect(error).toBeDefined();
      }
    });
  });
});