package groups

import (
	"reflect"
	"testing"
)

func TestParseGroup(t *testing.T) {
	data := []byte(`root:x:0:
# comment

wheel:x:10:alice,bob
developers:x:1500:alice
empty:x:1600:
broken:x:notanumber:x
short:x:5
`)
	got := parseGroup(data)
	if len(got) != 4 {
		t.Fatalf("expected 4 valid groups, got %d: %+v", len(got), got)
	}

	wheel := got[1]
	if wheel.Name != "wheel" || wheel.GID != 10 || !wheel.System ||
		!reflect.DeepEqual(wheel.Members, []string{"alice", "bob"}) {
		t.Errorf("wheel parsed wrong: %+v", wheel)
	}

	dev := got[2]
	if dev.GID != 1500 || dev.System {
		t.Errorf("developers should be a non-system group: %+v", dev)
	}

	empty := got[3]
	if len(empty.Members) != 0 {
		t.Errorf("empty group should have no members, got %v", empty.Members)
	}
}

func TestValidateGroupName(t *testing.T) {
	for _, tt := range []struct {
		name  string
		value string
		valid bool
	}{
		{name: "wheel", value: "wheel", valid: true},
		{name: "underscore prefix", value: "_svc", valid: true},
		{name: "dev-team", value: "dev-team", valid: true},
		{name: "alphanumeric", value: "g1", valid: true},
		{name: "empty", value: "", valid: false},
		{name: "flag injection", value: "-x", valid: false},
		{name: "uppercase", value: "Wheel", valid: false},
		{name: "comma", value: "a,b", valid: false},
		{name: "shell metachar", value: "foo;rm", valid: false},
		{name: "leading digit", value: "1grp", valid: false},
	} {
		t.Run(tt.name, func(t *testing.T) {
			err := validateGroupName(tt.value)
			if tt.valid && err != nil {
				t.Errorf("validateGroupName(%q) = %v, want nil", tt.value, err)
			}
			if !tt.valid && err == nil {
				t.Errorf("validateGroupName(%q) = nil, want error", tt.value)
			}
		})
	}
}
