package zddc

import "testing"

func TestParseVerbSetRoundTrip(t *testing.T) {
	cases := []struct {
		in  string
		out string
	}{
		{"", ""},
		{"r", "r"},
		{"rw", "rw"},
		{"wr", "rw"},      // canonical reorder
		{"rwcd", "rwcd"},
		{"adcwr", "rwcda"}, // canonical reorder
		{"RWCDA", "rwcda"}, // case-insensitive
		{" r w c ", "rwc"}, // whitespace tolerated
	}
	for _, tc := range cases {
		v, ok := ParseVerbSet(tc.in)
		if !ok {
			t.Errorf("ParseVerbSet(%q) ok=false", tc.in)
			continue
		}
		if got := v.String(); got != tc.out {
			t.Errorf("ParseVerbSet(%q).String() = %q, want %q", tc.in, got, tc.out)
		}
	}
}

func TestParseVerbSetUnknownLetter(t *testing.T) {
	if _, ok := ParseVerbSet("rwx"); ok {
		t.Errorf("ParseVerbSet(\"rwx\") = ok=true, want false")
	}
}

func TestVerbSetHasAndUnion(t *testing.T) {
	rw, _ := ParseVerbSet("rw")
	cd, _ := ParseVerbSet("cd")
	if !rw.Has(VerbR) {
		t.Errorf("rw should have R")
	}
	if rw.Has(VerbC) {
		t.Errorf("rw should not have C")
	}
	if got := rw.Union(cd).String(); got != "rwcd" {
		t.Errorf("rw|cd = %q, want rwcd", got)
	}
}

func TestIsPrincipalRole(t *testing.T) {
	cases := map[string]bool{
		"alice@example.com":  false,
		"*@example.com":      false,
		"alice@*":            false,
		"_doc_controller":    true,
		"vendor_acme":        true,
		"*":                  true, // legacy bare wildcard — treated as role-or-pattern
	}
	for in, want := range cases {
		if got := IsPrincipalRole(in); got != want {
			t.Errorf("IsPrincipalRole(%q) = %v, want %v", in, got, want)
		}
	}
}

func TestRoleMembersUnionAcrossCascade(t *testing.T) {
	chain := PolicyChain{
		Levels: []ZddcFile{
			// root: role defined with one member
			{Roles: map[string]Role{
				"editors": {Members: []string{"alice@example.com"}},
			}},
			// child: ADDS a member (union, not shadow)
			{Roles: map[string]Role{
				"editors": {Members: []string{"bob@example.com"}},
			}},
		},
		HasAnyFile: true,
	}
	got := RoleMembers(chain, 1, "editors")
	if len(got) != 2 {
		t.Fatalf("union: got %v, want both alice + bob", got)
	}
	has := func(s string) bool {
		for _, g := range got {
			if g == s {
				return true
			}
		}
		return false
	}
	if !has("alice@example.com") || !has("bob@example.com") {
		t.Errorf("union: got %v, want alice + bob", got)
	}
	// At root level, only the root definition is in the visible chain.
	got = RoleMembers(chain, 0, "editors")
	if len(got) != 1 || got[0] != "alice@example.com" {
		t.Errorf("root visibility: got %v, want [alice]", got)
	}
}

func TestRoleMembersResetBreaksUnion(t *testing.T) {
	chain := PolicyChain{
		Levels: []ZddcFile{
			// root
			{Roles: map[string]Role{
				"editors": {Members: []string{"alice@example.com"}},
			}},
			// mid: reset — ancestors above this are excluded for editors
			{Roles: map[string]Role{
				"editors": {Members: []string{"carol@example.com"}, Reset: true},
			}},
			// leaf: still unions on top of the reset level
			{Roles: map[string]Role{
				"editors": {Members: []string{"dave@example.com"}},
			}},
		},
		HasAnyFile: true,
	}
	got := RoleMembers(chain, 2, "editors")
	// Expect carol (reset level) + dave (leaf), NOT alice (excluded by reset).
	if len(got) != 2 {
		t.Fatalf("reset: got %v, want carol + dave only", got)
	}
	for _, g := range got {
		if g == "alice@example.com" {
			t.Errorf("reset should have excluded alice; got %v", got)
		}
	}
}

func TestMatchesPrincipalLegacyPatternFallback(t *testing.T) {
	// No roles defined; bare "*" and "*example.com" must still match
	// via legacy email-pattern semantics.
	chain := PolicyChain{
		Levels:     []ZddcFile{{}},
		HasAnyFile: true,
	}
	if !MatchesPrincipal("*", "alice@example.com", chain, 0) {
		t.Errorf("bare * should match any email via legacy fallback")
	}
	if !MatchesPrincipal("*example.com", "alice@example.com", chain, 0) {
		t.Errorf("*example.com should match alice@example.com via legacy fallback")
	}
}

func TestMatchesPrincipalRoleNamePrefersRole(t *testing.T) {
	// When a role is defined, the role match wins; legacy fallback is
	// not consulted.
	chain := PolicyChain{
		Levels: []ZddcFile{{
			Roles: map[string]Role{
				"vendor_acme": {Members: []string{"*@acme.com"}},
			},
		}},
		HasAnyFile: true,
	}
	if !MatchesPrincipal("vendor_acme", "rep@acme.com", chain, 0) {
		t.Errorf("rep@acme.com should match role vendor_acme")
	}
	if MatchesPrincipal("vendor_acme", "rep@other.com", chain, 0) {
		t.Errorf("rep@other.com should NOT match role vendor_acme — fallback to pattern would wrongly succeed")
	}
}
