package zone

import (
	"context"
	"path/filepath"
	"testing"

	"github.com/flothus/tmux-xterm-research/server-go/internal/harness/store"
)

func newSvc(t *testing.T) *Service {
	t.Helper()
	tmp := t.TempDir()
	st, err := store.Open(filepath.Join(tmp, "harness.db"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { st.Close() })
	return New(st)
}

func TestMatch(t *testing.T) {
	cases := []struct {
		path  string
		globs []string
		want  bool
	}{
		{"client/src/Foo.vue", []string{"client/**/*"}, true},
		{"server-go/main.go", []string{"client/**/*"}, false},
		{"client/src/sub/x.ts", []string{"client/**/*"}, true},
		{"docs/x.md", []string{"docs/"}, true},
		{"src/foo.ts", []string{"src/*.ts"}, true},
	}
	for _, c := range cases {
		got := Match(c.path, c.globs)
		if got != c.want {
			t.Errorf("Match(%q, %v) = %v, want %v", c.path, c.globs, got, c.want)
		}
	}
}

func TestRegisterAndLookupByPath(t *testing.T) {
	s := newSvc(t)
	ctx := context.Background()
	_ = s.Register(ctx, Zone{ID: "fe", Name: "frontend", PathGlobs: []string{"client/**/*"}})
	_ = s.Register(ctx, Zone{ID: "be", Name: "backend", PathGlobs: []string{"server-go/**/*"}})
	id, err := s.LookupByPath(ctx, "client/src/Foo.vue")
	if err != nil {
		t.Fatal(err)
	}
	if id != "fe" {
		t.Errorf("lookup = %s, want fe", id)
	}
	id, err = s.LookupByPath(ctx, "server-go/main.go")
	if err != nil {
		t.Fatal(err)
	}
	if id != "be" {
		t.Errorf("lookup = %s, want be", id)
	}
	id, _ = s.LookupByPath(ctx, "README.md")
	if id != "" {
		t.Errorf("unmatched path = %q, want empty", id)
	}
}
