package workspace

import (
	"path/filepath"
	"strings"
	"testing"

	"github.com/google/uuid"
	"github.com/stretchr/testify/require"
)

func TestValidateSlug(t *testing.T) {
	t.Parallel()
	good := []string{"a", "ab", "ws-1", "abc-def", "x9"}
	bad := []string{"", "-x", "x-", "Ab", "a--b is invalid? let's check: a--b"}
	for _, s := range good {
		require.NoError(t, ValidateSlug(s), s)
	}
	for _, s := range bad {
		// "a--b" 实际是合法的（regex 允许内部连字符）；剔除该用例
		if s == "a--b is invalid? let's check: a--b" {
			continue
		}
		require.Error(t, ValidateSlug(s), s)
	}
}

func TestValidateBranch(t *testing.T) {
	t.Parallel()
	require.NoError(t, ValidateBranch("main"))
	require.NoError(t, ValidateBranch("feat/foo-bar"))
	require.NoError(t, ValidateBranch("release.1"))
	require.Error(t, ValidateBranch("-x"))
	require.Error(t, ValidateBranch("/x"))
	require.Error(t, ValidateBranch("a..b"))
	require.Error(t, ValidateBranch(""))
	require.Error(t, ValidateBranch(strings.Repeat("a", 201)))
}

func TestValidateRemoteURL(t *testing.T) {
	t.Parallel()
	require.NoError(t, ValidateRemoteURL("https://github.com/x/y.git"))
	require.NoError(t, ValidateRemoteURL("git@github.com:x/y.git"))
	require.NoError(t, ValidateRemoteURL("ssh://git@host/x.git"))
	require.Error(t, ValidateRemoteURL("file:///etc/passwd"))
	require.Error(t, ValidateRemoteURL("ftp://x"))
	// 内嵌凭据（user:pass@）须被拒绝，避免绕过本系统凭据存储
	require.Error(t, ValidateRemoteURL("https://user:pass@github.com/x/y.git"))
}

func TestPaths(t *testing.T) {
	t.Parallel()
	id := uuid.MustParse("11111111-1111-1111-1111-111111111111")
	// 用 filepath.Base 做断言以跨平台兼容（Windows 下 filepath.Join 返回反斜杠）。
	require.Equal(t, "main", filepath.Base(MainPath("/data", id)))
	require.True(t, strings.Contains(WorktreePath("/data", id, "feat/x"), "feat_x"))
	require.Equal(t, "tmp", filepath.Base(TmpDir("/data")))
}
