import {
  describe,
  expect,
  it
} from 'vitest';

import {
  formatAppRamLabel,
  formatKilobytesAsMegabytes,
  sumWorkingSetKb
} from './electron-app-metrics.rules';
import type { ElectronAppMetricsSnapshot } from './electron-app-metrics.rules';

function createSnapshot(
  processes: ElectronAppMetricsSnapshot['processes']
): ElectronAppMetricsSnapshot {
  return {
    collectedAt: 1,
    processes
  };
}

describe('sumWorkingSetKb', () => {
  it('sums working set across processes that report memory', () => {
    const total = sumWorkingSetKb([{ pid: 1, type: 'Browser', workingSetKb: 1024 }, { pid: 2, type: 'GPU', workingSetKb: 512 }]);

    expect(total).toBe(1536);
  });

  it('ignores processes without memory readings', () => {
    const total = sumWorkingSetKb([{ pid: 1, type: 'Browser', workingSetKb: 2048 }, { pid: 2, type: 'Unknown', workingSetKb: null }]);

    expect(total).toBe(2048);
  });

  it('returns null when no process reports memory', () => {
    expect(sumWorkingSetKb([{ pid: 1, type: 'Browser', workingSetKb: null }])).toBeNull();
  });
});

describe('formatKilobytesAsMegabytes', () => {
  it('rounds large values to whole megabytes', () => {
    expect(formatKilobytesAsMegabytes(412 * 1024)).toBe('412 MB');
  });

  it('keeps one decimal for medium values', () => {
    expect(formatKilobytesAsMegabytes(15.4 * 1024)).toBe('15.4 MB');
  });

  it('keeps two decimals for small values', () => {
    expect(formatKilobytesAsMegabytes(1.25 * 1024)).toBe('1.25 MB');
  });
});

describe('formatAppRamLabel', () => {
  it('formats total working set as a compact RAM label', () => {
    const browser = { pid: 1, type: 'Browser', workingSetKb: 300 * 1024 };
    const gpu = { pid: 2, type: 'GPU', workingSetKb: 112 * 1024 };
    const label = formatAppRamLabel(createSnapshot([browser, gpu]));

    expect(label).toBe('412 MB');
  });

  it('returns null when metrics contain no memory readings', () => {
    expect(formatAppRamLabel(createSnapshot([{ pid: 1, type: 'Browser', workingSetKb: null }]))).toBeNull();
  });
});
