package panelacl

import "testing"

// TestPermString covers the Perm→token rendering.
func TestPermString(t *testing.T) {
	cases := map[Perm]string{PermNone: "none", PermRead: "read", PermWrite: "write"}
	for p, want := range cases {
		if got := p.String(); got != want {
			t.Errorf("Perm(%d).String() = %q, want %q", p, got, want)
		}
	}
}

// TestPlaceAndDeletePanel covers PlacePanel (organizational-only record that
// stays open) and DeletePanel (present + absent).
func TestPlaceAndDeletePanel(t *testing.T) {
	s := newStore(t)
	if _, err := s.CreateFolder("f1", "Folder 1", "", "alice"); err != nil {
		t.Fatal(err)
	}

	// Placing a legacy panel into a folder must not lock it (no owner record).
	if err := s.PlacePanel("legacy", "f1", 2.5); err != nil {
		t.Fatalf("PlacePanel: %v", err)
	}
	if got := s.PanelPerm("legacy", "bob", nil); got != PermWrite {
		t.Errorf("placed legacy panel perm = %v, want write", got)
	}

	// DeletePanel on a missing record is a no-op success.
	if err := s.DeletePanel("never"); err != nil {
		t.Errorf("DeletePanel missing: %v", err)
	}
	// DeletePanel on the placed record removes it.
	if err := s.DeletePanel("legacy"); err != nil {
		t.Fatalf("DeletePanel: %v", err)
	}
}

// TestFoldersAndGetFolder covers the folder accessors, FolderPerm on an owner
// vs a stranger, and reload from the persisted index.
func TestFoldersAndGetFolder(t *testing.T) {
	dir := t.TempDir()
	s, err := New(dir)
	if err != nil {
		t.Fatal("New:", err)
	}
	if _, err := s.CreateFolder("root", "Root", "", "alice"); err != nil {
		t.Fatal(err)
	}

	all := s.Folders()
	if len(all) != 1 {
		t.Fatalf("Folders: want 1, got %d", len(all))
	}
	if f, err := s.GetFolder("root"); err != nil || f.Name != "Root" {
		t.Errorf("GetFolder = %+v, %v", f, err)
	}
	if _, err := s.GetFolder("ghost"); err != ErrNotFound {
		t.Errorf("GetFolder missing: want ErrNotFound, got %v", err)
	}

	// Owner has write on the folder; an unrelated user has none.
	if got := s.FolderPerm("root", "alice", nil); got != PermWrite {
		t.Errorf("owner FolderPerm = %v, want write", got)
	}
	if got := s.FolderPerm("root", "bob", nil); got != PermNone {
		t.Errorf("stranger FolderPerm = %v, want none", got)
	}

	// Reload: a fresh Store over the same dir still sees the folder.
	s2, err := New(dir)
	if err != nil {
		t.Fatalf("reopen: %v", err)
	}
	if _, err := s2.GetFolder("root"); err != nil {
		t.Errorf("reloaded GetFolder: %v", err)
	}
}
