package git_test

import (
	"path/filepath"
	"testing"

	"bit.admedia.com/scm/ad/adpilot-indexing-repo-sync.com/internal/config"
	"bit.admedia.com/scm/ad/adpilot-indexing-repo-sync.com/internal/git"
)

func TestCloneURL(t *testing.T) {
	url, err := git.CloneURL("https://bit.admedia.com", "ad/adpilot-indexing-repo-sync.com")
	if err != nil {
		t.Fatalf("CloneURL: %v", err)
	}
	want := "https://bit.admedia.com/scm/ad/adpilot-indexing-repo-sync.com.git"
	if url != want {
		t.Fatalf("got %q, want %q", url, want)
	}
}

func TestCloneURLStripsProviderPrefix(t *testing.T) {
	cases := []struct{ repoID, want string }{
		{"ad/adpilot-indexing-repo-sync.com", "https://bit.admedia.com/scm/ad/adpilot-indexing-repo-sync.com.git"},
		{"bitbucket_server:AD/admediacrons.com", "https://bit.admedia.com/scm/ad/admediacrons.com.git"},
		{"bitbucket_server:AD/store.com", "https://bit.admedia.com/scm/ad/store.com.git"},
	}
	for _, c := range cases {
		got, err := git.CloneURL("https://bit.admedia.com", c.repoID)
		if err != nil {
			t.Fatalf("CloneURL(%q): %v", c.repoID, err)
		}
		if got != c.want {
			t.Errorf("CloneURL(%q) = %q, want %q", c.repoID, got, c.want)
		}
	}
}

func TestWorkspaceDir(t *testing.T) {
	cfg := config.Config{Git: config.GitConfig{WorkspacePath: "./data/repos"}}
	dir, err := git.WorkspaceDir(cfg, "ad/example-repo")
	if err != nil {
		t.Fatalf("WorkspaceDir: %v", err)
	}
	want := filepath.Join("./data/repos", "ad__example-repo")
	if dir != want {
		t.Fatalf("got %q, want %q", dir, want)
	}

	gatewayName := git.WorkspaceDirName("github:org/repo")
	if gatewayName != "github__org__repo" {
		t.Fatalf("gateway dir name: got %q, want %q", gatewayName, "github__org__repo")
	}
}

func TestEnsureUnderWorkspace(t *testing.T) {
	workspace := t.TempDir()
	inside := filepath.Join(workspace, "ad__repo")
	if err := git.EnsureUnderWorkspace(workspace, inside); err != nil {
		t.Fatalf("expected inside path to be allowed: %v", err)
	}
	outside := filepath.Join(t.TempDir(), "outside")
	if err := git.EnsureUnderWorkspace(workspace, outside); err == nil {
		t.Fatal("expected outside path to be rejected")
	}
}
