package m9zApi

import "testing"

func TestNormalizeLoopCount(t *testing.T) {
	tests := []struct {
		name string
		in   int
		want int
	}{
		{name: "default when empty", in: 0, want: defaultLoopCount},
		{name: "default when negative", in: -1, want: defaultLoopCount},
		{name: "keeps valid value", in: 6, want: 6},
		{name: "clamps max value", in: 12, want: maxLoopCount},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := normalizeLoopCount(tt.in); got != tt.want {
				t.Fatalf("normalizeLoopCount(%d) = %d, want %d", tt.in, got, tt.want)
			}
		})
	}
}

func TestMonitorDisplayLoopCountAlwaysUsesMaxLoopCount(t *testing.T) {
	if got := monitorDisplayLoopCount(); got != maxLoopCount {
		t.Fatalf("monitorDisplayLoopCount() = %d, want %d", got, maxLoopCount)
	}
}

func TestBuildDemoDeviceStatus2KeepsDisplayLoopsIndependentFromScanCount(t *testing.T) {
	scanConfigManager.mu.Lock()
	oldLoopCount := scanConfigManager.loopCount
	scanConfigManager.loopCount = 6
	scanConfigManager.mu.Unlock()
	t.Cleanup(func() {
		scanConfigManager.mu.Lock()
		scanConfigManager.loopCount = oldLoopCount
		scanConfigManager.mu.Unlock()
	})

	status := buildDemoDeviceStatus2()
	if got := len(status.Loops); got != monitorDisplayLoopCount() {
		t.Fatalf("len(status.Loops) = %d, want %d", got, monitorDisplayLoopCount())
	}
	if got := status.ScanDeviceCount; got != 6 {
		t.Fatalf("status.ScanDeviceCount = %d, want 6", got)
	}
	if !status.Loops[5].HasFault {
		t.Fatal("status.Loops[5].HasFault = false, want true for the last scanned loop")
	}
	if status.Loops[6].HasFault {
		t.Fatal("status.Loops[6].HasFault = true, want false outside the scan loop count")
	}
}
