package zddc

import (
	"os"
	"path/filepath"
	"testing"
)

// resetCache empties the package-level policyCache so each test starts clean.
func resetCache() {
	policyCache.Range(func(k, _ any) bool {
		policyCache.Delete(k)
		return true
	})
}

func writeZddc(t *testing.T, dir, body string) {
	t.Helper()
	if err := os.WriteFile(filepath.Join(dir, ".zddc"), []byte(body), 0o644); err != nil {
		t.Fatalf("write .zddc in %s: %v", dir, err)
	}
}

func TestEffectivePolicy(t *testing.T) {
	t.Run("no .zddc files anywhere: chain has no files", func(t *testing.T) {
		resetCache()
		root := t.TempDir()
		leaf := filepath.Join(root, "a", "b")
		if err := os.MkdirAll(leaf, 0o755); err != nil {
			t.Fatal(err)
		}

		chain, err := EffectivePolicy(root, leaf)
		if err != nil {
			t.Fatal(err)
		}
		if chain.HasAnyFile {
			t.Errorf("HasAnyFile = true, want false")
		}
		// One level per directory (root, root/a, root/a/b) = 3
		if got, want := len(chain.Levels), 3; got != want {
			t.Errorf("len(Levels) = %d, want %d", got, want)
		}
	})

	t.Run("cascade order is root → leaf", func(t *testing.T) {
		resetCache()
		root := t.TempDir()
		mid := filepath.Join(root, "a")
		leaf := filepath.Join(mid, "b")
		if err := os.MkdirAll(leaf, 0o755); err != nil {
			t.Fatal(err)
		}
		writeZddc(t, root, "acl:\n  allow:\n    - root@example.com\n")
		writeZddc(t, leaf, "acl:\n  allow:\n    - leaf@example.com\n")

		chain, err := EffectivePolicy(root, leaf)
		if err != nil {
			t.Fatal(err)
		}
		if !chain.HasAnyFile {
			t.Error("HasAnyFile = false, want true")
		}
		if len(chain.Levels) != 3 {
			t.Fatalf("len(Levels) = %d, want 3", len(chain.Levels))
		}
		if got := chain.Levels[0].ACL.Allow; len(got) != 1 || got[0] != "root@example.com" {
			t.Errorf("root level Allow = %v, want [root@example.com]", got)
		}
		if got := chain.Levels[1].ACL.Allow; len(got) != 0 {
			t.Errorf("middle level Allow = %v, want empty", got)
		}
		if got := chain.Levels[2].ACL.Allow; len(got) != 1 || got[0] != "leaf@example.com" {
			t.Errorf("leaf level Allow = %v, want [leaf@example.com]", got)
		}
	})

	t.Run("dirPath outside fsRoot returns empty chain", func(t *testing.T) {
		resetCache()
		root := t.TempDir()
		other := t.TempDir() // unrelated tree

		chain, err := EffectivePolicy(root, other)
		if err != nil {
			t.Fatal(err)
		}
		if chain.HasAnyFile {
			t.Error("HasAnyFile = true, want false for out-of-root path")
		}
		if len(chain.Levels) != 0 {
			t.Errorf("len(Levels) = %d, want 0", len(chain.Levels))
		}
	})

	t.Run("malformed .zddc yields empty level but does not abort the chain", func(t *testing.T) {
		resetCache()
		root := t.TempDir()
		leaf := filepath.Join(root, "a")
		if err := os.MkdirAll(leaf, 0o755); err != nil {
			t.Fatal(err)
		}
		// Garbage YAML
		writeZddc(t, root, "::: not yaml :::")
		writeZddc(t, leaf, "acl:\n  allow:\n    - leaf@example.com\n")

		chain, err := EffectivePolicy(root, leaf)
		if err != nil {
			t.Fatal(err)
		}
		if !chain.HasAnyFile {
			t.Error("HasAnyFile = false, want true (malformed file still counts as present)")
		}
		// Root level parsed empty (parse error path), leaf level has the rule
		if got := chain.Levels[0].ACL.Allow; len(got) != 0 {
			t.Errorf("root level Allow = %v, want empty (parse error)", got)
		}
		if got := chain.Levels[1].ACL.Allow; len(got) != 1 || got[0] != "leaf@example.com" {
			t.Errorf("leaf level Allow = %v, want [leaf@example.com]", got)
		}
	})

	t.Run("dirPath equal to fsRoot has single level", func(t *testing.T) {
		resetCache()
		root := t.TempDir()
		writeZddc(t, root, "acl:\n  allow:\n    - root@example.com\n")

		chain, err := EffectivePolicy(root, root)
		if err != nil {
			t.Fatal(err)
		}
		if len(chain.Levels) != 1 {
			t.Errorf("len(Levels) = %d, want 1", len(chain.Levels))
		}
	})
}

func TestEffectivePolicyEndToEnd(t *testing.T) {
	resetCache()
	root := t.TempDir()
	pub := filepath.Join(root, "public")
	priv := filepath.Join(root, "private")
	for _, d := range []string{pub, priv} {
		if err := os.MkdirAll(d, 0o755); err != nil {
			t.Fatal(err)
		}
	}
	writeZddc(t, priv, "acl:\n  allow:\n    - alice@example.com\n  deny:\n    - bob@example.com\n")

	// public/: no .zddc on the chain → default allow for everyone
	chainPub, _ := EffectivePolicy(root, pub)
	if !AllowedWithChain(chainPub, "anyone@anywhere.com") {
		t.Error("public/ should be open when no .zddc files exist on the chain")
	}

	// private/: has rules → only alice gets in
	chainPriv, _ := EffectivePolicy(root, priv)
	if !AllowedWithChain(chainPriv, "alice@example.com") {
		t.Error("alice should be allowed in private/")
	}
	if AllowedWithChain(chainPriv, "bob@example.com") {
		t.Error("bob should be denied in private/")
	}
	if AllowedWithChain(chainPriv, "carol@example.com") {
		t.Error("carol (unlisted) should be denied in private/ when files exist")
	}
}

func TestInvalidateCache(t *testing.T) {
	t.Run("invalidates exact path", func(t *testing.T) {
		resetCache()
		root := t.TempDir()
		dir := filepath.Join(root, "a")
		if err := os.MkdirAll(dir, 0o755); err != nil {
			t.Fatal(err)
		}

		_, _ = EffectivePolicy(root, dir)
		if _, ok := policyCache.Load(dir); !ok {
			t.Fatal("cache should contain entry after EffectivePolicy")
		}
		InvalidateCache(dir)
		if _, ok := policyCache.Load(dir); ok {
			t.Error("cache should not contain entry after InvalidateCache")
		}
	})

	t.Run("invalidates descendants when parent changes", func(t *testing.T) {
		resetCache()
		root := t.TempDir()
		mid := filepath.Join(root, "a")
		leaf := filepath.Join(mid, "b")
		sibling := filepath.Join(root, "c")
		for _, d := range []string{leaf, sibling} {
			if err := os.MkdirAll(d, 0o755); err != nil {
				t.Fatal(err)
			}
		}

		// Populate cache for mid, leaf, sibling
		_, _ = EffectivePolicy(root, mid)
		_, _ = EffectivePolicy(root, leaf)
		_, _ = EffectivePolicy(root, sibling)
		for _, p := range []string{mid, leaf, sibling} {
			if _, ok := policyCache.Load(p); !ok {
				t.Fatalf("cache missing %s", p)
			}
		}

		// Change a .zddc in mid → InvalidateCache(mid) drops mid and leaf, keeps sibling
		InvalidateCache(mid)
		if _, ok := policyCache.Load(mid); ok {
			t.Error("mid should be invalidated")
		}
		if _, ok := policyCache.Load(leaf); ok {
			t.Error("leaf (descendant of mid) should be invalidated")
		}
		if _, ok := policyCache.Load(sibling); !ok {
			t.Error("sibling should remain cached")
		}
	})

	t.Run("invalidating a path does not invalidate string-prefix-but-not-path-prefix", func(t *testing.T) {
		resetCache()
		root := t.TempDir()
		// "/tmp/foo" should not invalidate "/tmp/foobar" — the implementation guards
		// this by appending the separator before HasPrefix.
		foo := filepath.Join(root, "foo")
		foobar := filepath.Join(root, "foobar")
		for _, d := range []string{foo, foobar} {
			if err := os.MkdirAll(d, 0o755); err != nil {
				t.Fatal(err)
			}
		}
		_, _ = EffectivePolicy(root, foo)
		_, _ = EffectivePolicy(root, foobar)

		InvalidateCache(foo)
		if _, ok := policyCache.Load(foo); ok {
			t.Error("foo should be invalidated")
		}
		if _, ok := policyCache.Load(foobar); !ok {
			t.Error("foobar should NOT be invalidated by InvalidateCache(foo)")
		}
	})
}
