package workerload

import (
	"os"
	"path/filepath"
	"testing"
	"time"
)

func TestSystemSamplerReadsCgroupV2(t *testing.T) {
	root := t.TempDir()
	writeSamplerFixture(t, filepath.Join(root, "memory.current"), "50\n")
	writeSamplerFixture(t, filepath.Join(root, "memory.max"), "100\n")
	writeSamplerFixture(t, filepath.Join(root, "cpu.max"), "100000 100000\n")
	writeSamplerFixture(t, filepath.Join(root, "cpu.stat"), "usage_usec 100000\nnr_throttled 1\n")
	sampler := NewSystemSamplerAt(root)
	first := sampler.Sample(2, 10)
	if first.MemoryCurrentBytes != 50 || first.MemoryLimitBytes != 100 || first.DBConnections != 2 {
		t.Fatalf("first sample=%+v", first)
	}
	time.Sleep(10 * time.Millisecond)
	writeSamplerFixture(t, filepath.Join(root, "cpu.stat"), "usage_usec 105000\nnr_throttled 2\n")
	second := sampler.Sample(3, 10)
	if second.CPUUtilization <= 0 || !second.CPUThrottled {
		t.Fatalf("second sample=%+v", second)
	}
}

func writeSamplerFixture(t *testing.T, path, value string) {
	t.Helper()
	if err := os.WriteFile(path, []byte(value), 0o600); err != nil {
		t.Fatal(err)
	}
}
