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")
	}
}

func sameStrs(a, b []string) bool {
	if len(a) != len(b) {
		return false
	}
	for i := range a {
		if a[i] != b[i] {
			return false
		}
	}
	return true
}

// TestRolesForPrincipalInChain — "which roles do I hold here?" honours
// member unions across the visible chain, wildcard members, and reports
// nothing for non-members / empty email. Output is sorted.
func TestRolesForPrincipalInChain(t *testing.T) {
	chain := buildChain(
		ZddcFile{
			Roles: map[string]Role{
				"document_controller": {Members: []string{"dc@example.com"}},
				"project_team":        {Members: []string{"*@example.com"}},
			},
			ACL: aclOpen(map[string]string{"*@example.com": "r"}),
		},
		// A deeper level adds another DC; the root members still union in.
		ZddcFile{
			Roles: map[string]Role{
				"document_controller": {Members: []string{"vendor-dc@example.com"}},
			},
		},
	)

	if got := RolesForPrincipalInChain(chain, "dc@example.com"); !sameStrs(got, []string{"document_controller", "project_team"}) {
		t.Errorf("dc: got %v, want [document_controller project_team]", got)
	}
	if got := RolesForPrincipalInChain(chain, "alice@example.com"); !sameStrs(got, []string{"project_team"}) {
		t.Errorf("alice: got %v, want [project_team]", got)
	}
	if got := RolesForPrincipalInChain(chain, "x@other.com"); len(got) != 0 {
		t.Errorf("outsider: got %v, want none", got)
	}
	if got := RolesForPrincipalInChain(chain, ""); got != nil {
		t.Errorf("empty email: got %v, want nil", got)
	}
}

// A role defined above an inherit:false fence is invisible below it, so
// membership there reports no such role.
func TestRolesForPrincipalInChain_FenceHidesAncestorRole(t *testing.T) {
	chain := buildChain(
		ZddcFile{Roles: map[string]Role{"document_controller": {Members: []string{"dc@example.com"}}}},
		ZddcFile{ACL: aclFenced(map[string]string{"*@vendor.com": "rwcd"}, false)},
	)
	if got := RolesForPrincipalInChain(chain, "dc@example.com"); len(got) != 0 {
		t.Errorf("role above fence must be invisible below it; got %v", got)
	}
}
