import { describe, it, expect } from 'vitest';
import { _RMM_WORKER_INTERNALS } from './worker';

describe('extractResult', () => {
  const { extractResult } = _RMM_WORKER_INTERNALS;
  const deviceUid = 'dev-1';

  it('returns done=false while jobStatus is running', () => {
    const r = extractResult({ jobStatus: 'running', stdOut: null }, deviceUid);
    expect(r.done).toBe(false);
    expect(r.exitCode).toBeNull();
  });

  it('returns done=true with exitCode 0 on succeeded', () => {
    const r = extractResult(
      { jobStatus: 'succeeded', stdOut: '{"ok":true}', stdErr: '', errorCode: 0 },
      deviceUid
    );
    expect(r.done).toBe(true);
    expect(r.exitCode).toBe(0);
    expect(r.stdout).toBe('{"ok":true}');
  });

  it('returns done=true with exitCode 1 on failed (no errorCode given)', () => {
    const r = extractResult({ jobStatus: 'failed', stdErr: 'boom' }, deviceUid);
    expect(r.done).toBe(true);
    expect(r.exitCode).toBe(1);
    expect(r.stderr).toBe('boom');
  });

  it('uses per-device result when results array present', () => {
    const r = extractResult(
      {
        jobStatus: 'running',
        results: [
          { deviceUid: 'dev-1', jobStatus: 'succeeded', stdOut: 'A', errorCode: 0 },
          { deviceUid: 'dev-2', jobStatus: 'running', stdOut: null },
        ],
      },
      'dev-1'
    );
    expect(r.done).toBe(true);
    expect(r.stdout).toBe('A');
  });

  it('falls back to first result when device-specific not found', () => {
    const r = extractResult(
      {
        jobStatus: 'succeeded',
        results: [
          { jobStatus: 'succeeded', stdOut: 'fallback', errorCode: 0 },
        ],
      },
      'dev-X'
    );
    expect(r.done).toBe(true);
    expect(r.stdout).toBe('fallback');
  });
});
