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 TestRoleMembersClosestLeafWins(t *testing.T) {
	chain := PolicyChain{
		Levels: []ZddcFile{
			// root: role defined with one set of members
			{Roles: map[string]Role{
				"editors": {Members: []string{"alice@example.com"}},
			}},
			// child: shadows with a different set
			{Roles: map[string]Role{
				"editors": {Members: []string{"bob@example.com"}},
			}},
		},
		HasAnyFile: true,
	}
	got := RoleMembers(chain, 1, "editors", ModeDelegated)
	if len(got) != 1 || got[0] != "bob@example.com" {
		t.Errorf("leaf shadow failed: %v", got)
	}
	// At root level, only the root definition is visible.
	got = RoleMembers(chain, 0, "editors", ModeDelegated)
	if len(got) != 1 || got[0] != "alice@example.com" {
		t.Errorf("root visibility failed: %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, ModeDelegated) {
		t.Errorf("bare * should match any email via legacy fallback")
	}
	if !MatchesPrincipal("*example.com", "alice@example.com", chain, 0, ModeDelegated) {
		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, ModeDelegated) {
		t.Errorf("rep@acme.com should match role vendor_acme")
	}
	if MatchesPrincipal("vendor_acme", "rep@other.com", chain, 0, ModeDelegated) {
		t.Errorf("rep@other.com should NOT match role vendor_acme — fallback to pattern would wrongly succeed")
	}
}
