import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';
import { homedir, tmpdir } from 'os';
import { join, resolve } from 'path';
import { describe, expect, it } from 'vitest';
import { AuditLogger } from './logger.js';

describe('AuditLogger', () => {
  it('expands ~ in audit path before writing logs', async () => {
    const previousHome = process.env.HOME;
    const tempHome = mkdtempSync(join(tmpdir(), 'flynn-audit-home-'));
    process.env.HOME = tempHome;

    try {
      // Sanity-check this process sees the temp home.
      expect(homedir()).toBe(tempHome);

      const logger = new AuditLogger({
        enabled: true,
        path: '~/.local/share/flynn/audit.log',
        max_size_mb: 10,
        keep_days: 30,
        levels: {
          tools: 'debug',
          sessions: 'debug',
          automation: 'debug',
        },
      });

      logger.systemStart('test-component');
      await logger.close();
      await new Promise((resolvePromise) => setTimeout(resolvePromise, 25));

      const loggerPath = (logger as unknown as { config: { path: string } }).config.path;
      const expectedPath = resolve(tempHome, '.local/share/flynn/audit.log');
      expect(loggerPath).toBe(expectedPath);
      expect(existsSync(expectedPath)).toBe(true);
      const content = readFileSync(expectedPath, 'utf-8');
      expect(content).toContain('"event_type":"system.start"');
      expect(content).toContain('"component":"test-component"');
    } finally {
      if (previousHome === undefined) {
        delete process.env.HOME;
      } else {
        process.env.HOME = previousHome;
      }
      rmSync(tempHome, { recursive: true, force: true });
    }
  });
});
