import { describe, it, expect, afterEach } from 'vitest';
import { processManager } from '../processManager.js';

describe('processManager', () => {
  afterEach(() => {
    for (const p of processManager.list()) {
      processManager.stop(p.id);
    }
  });

  it('starts a tracked process and returns metadata', () => {
    const info = processManager.start({
      label: 'echo',
      command: 'node',
      args: ['-e', 'console.log("ok")'],
      cwd: process.cwd(),
    });

    expect(info.label).toBe('echo');
    expect(info.command).toBe('node');
    expect(info.status).toBe('running');
    expect(info.args).toEqual(['-e', 'console.log("ok")']);
  });

  it('collects logs from a process', async () => {
    const info = processManager.start({
      label: 'echo',
      command: 'node',
      args: ['-e', 'console.log("line1"); console.log("line2")'],
      cwd: process.cwd(),
    });

    await new Promise((resolve) => setTimeout(resolve, 500));
    const { logs } = processManager.getLogs(info.id, 100);
    expect(logs).toContain('line1');
    expect(logs).toContain('line2');
  });

  it('reports a stopped process', async () => {
    const info = processManager.start({
      label: 'sleep',
      command: 'node',
      args: ['-e', 'setTimeout(() => {}, 60000)'],
      cwd: process.cwd(),
    });

    processManager.stop(info.id);
    await new Promise((resolve) => setTimeout(resolve, 200));

    const stopped = processManager.list().find((p) => p.id === info.id);
    expect(stopped?.status).toBe('stopped');
  });

  it('throws for an unknown process id', () => {
    expect(() => processManager.getLogs('not-a-real-id')).toThrow(/Unknown processId/);
  });
});
