import { HistoryLogger } from '../src/modules/historyLogger';
import * as fs from 'fs/promises';
import * as path from 'path';

// Mock fs module
jest.mock('fs/promises', () => ({
  mkdir: jest.fn().mockResolvedValue(undefined),
  appendFile: jest.fn().mockResolvedValue(undefined),
}));

describe('HistoryLogger', () => {
  // Save original environment and restore after tests
  const originalEnv = process.env;
  
  beforeEach(() => {
    // Reset mocks before each test
    jest.clearAllMocks();
    process.env = { ...originalEnv };
  });
  
  afterAll(() => {
    process.env = originalEnv;
  });

  it('should initialize with default context directory', () => {
    // Delete any context dir env variable to use default
    delete process.env.LAMPLIGHTER_CONTEXT_DIR;
    
    const logger = new HistoryLogger();
    
    // Check if mkdir was called with the default directory
    expect(fs.mkdir).toHaveBeenCalledWith('./lamplighter_context', { recursive: true });
  });

  it('should initialize with custom context directory from env', () => {
    // Set custom context directory
    process.env.LAMPLIGHTER_CONTEXT_DIR = './custom_context';
    
    const logger = new HistoryLogger();
    
    // Check if mkdir was called with the custom directory
    expect(fs.mkdir).toHaveBeenCalledWith('./custom_context', { recursive: true });
  });

  it('should append log messages to the log file', async () => {
    const logger = new HistoryLogger();
    const testMessage = 'Test log message';
    
    await logger.log(testMessage);
    
    // Check if appendFile was called with correct parameters
    expect(fs.appendFile).toHaveBeenCalledTimes(1);
    
    // Get the call arguments
    const callArgs = (fs.appendFile as jest.Mock).mock.calls[0];
    
    // Check file path - should end with history_log.md
    expect(callArgs[0]).toMatch(/history_log\.md$/);
    
    // Check message content
    expect(callArgs[1]).toMatch(new RegExp(`.*${testMessage}`));
    
    // Check encoding
    expect(callArgs[2]).toBe('utf-8');
  });

  it('should include timestamp in log message', async () => {
    const logger = new HistoryLogger();
    await logger.log('Test with timestamp');
    
    // Get the appended message
    const appendedMessage = (fs.appendFile as jest.Mock).mock.calls[0][1];
    
    // Timestamp format: [YYYY-MM-DD HH:MM:SS]
    expect(appendedMessage).toMatch(/^\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\]/);
  });
}); 