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

vi.mock('child_process', () => ({
  execFileSync: vi.fn(),
}));

import { execFileSync } from 'child_process';
import {
  buildComposeCgroupOverride,
  getComposeCgroupOverridePath,
  getTenantSystemdSlice,
} from './tenant-cgroups.js';
import { RUNTIME_STATE_DIR } from './config.js';

describe('tenant-cgroups', () => {
  afterEach(() => {
    vi.clearAllMocks();
  });

  it('maps a tenant passwd uid to a user slice name', () => {
    vi.mocked(execFileSync).mockReturnValue('john:x:2010:100::/home/john:/bin/bash\n');

    expect(getTenantSystemdSlice('john')).toBe('user-2010.slice');
  });

  it('returns null when tenant passwd lookup fails', () => {
    vi.mocked(execFileSync).mockImplementation(() => {
      throw new Error('missing');
    });

    expect(getTenantSystemdSlice('missing')).toBeNull();
  });

  it('builds a compose override file that sets cgroup_parent per service', () => {
    expect(
      buildComposeCgroupOverride(['web', 'worker'], 'user-2010.slice'),
    ).toBe(
      [
        'services:',
        '  web:',
        '    cgroup_parent: user-2010.slice',
        '  worker:',
        '    cgroup_parent: user-2010.slice',
        '',
      ].join('\n'),
    );
    expect(
      getComposeCgroupOverridePath('/tmp/app/docker-compose.yml', 'john'),
    ).toBe(
      `${RUNTIME_STATE_DIR}/compose-overrides/john/app.docker-compose.yml.nanoclaw.cgroup-parent.override.yml`,
    );
  });
});
