package bgtask

import (
	"testing"

	"github.com/go-logr/logr"
)

func TestLimitSharedWorkerCountPerKeyspace(t *testing.T) {
	tests := []struct {
		name        string
		maxShared   int
		maxPerKS    int
		count       int
		want        int
		wantExceeds bool
	}{
		{
			name:        "per keyspace config overrides shared config",
			maxShared:   64,
			maxPerKS:    8,
			count:       16,
			want:        8,
			wantExceeds: true,
		},
		{
			name:        "shared config is fallback",
			maxShared:   64,
			maxPerKS:    0,
			count:       80,
			want:        64,
			wantExceeds: true,
		},
		{
			name:      "zero disables limit when no fallback is configured",
			maxShared: 0,
			maxPerKS:  0,
			count:     80,
			want:      80,
		},
		{
			name:      "count under limit is unchanged",
			maxShared: 64,
			maxPerKS:  8,
			count:     4,
			want:      4,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			h := &handler{
				logger:                          logr.Discard(),
				maxSharedWorkerCount:            tt.maxShared,
				maxSharedWorkerCountPerKeyspace: tt.maxPerKS,
			}

			got := h.limitSharedWorkerCountPerKeyspace("ks1", tt.count)
			if got != tt.want {
				t.Fatalf("limitSharedWorkerCountPerKeyspace() = %d, want %d", got, tt.want)
			}

			gotExceeds := h.exceedsSharedWorkerCountPerKeyspaceLimit(tt.count)
			if gotExceeds != tt.wantExceeds {
				t.Fatalf("exceedsSharedWorkerCountPerKeyspaceLimit() = %v, want %v",
					gotExceeds, tt.wantExceeds)
			}
		})
	}
}
