package git

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

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

func TestWorktree_AddListRemove(t *testing.T) {
	t.Parallel()
	gitAvailable(t)
	bare := makeBareRepo(t)
	r := newTestRunner(t)
	main := filepath.Join(t.TempDir(), "main")
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()
	require.NoError(t, r.Clone(ctx, main, bare, "main", nil))

	feat := filepath.Join(filepath.Dir(main), "feat-x")
	require.NoError(t, r.WorktreeAdd(ctx, main, "feat-x", feat, ""))

	list, err := r.WorktreeList(ctx, main)
	require.NoError(t, err)
	require.GreaterOrEqual(t, len(list), 2)
	var found bool
	for _, w := range list {
		if w.Branch == "feat-x" {
			found = true
		}
	}
	require.True(t, found, "feat-x worktree not in list")

	require.NoError(t, r.WorktreeRemove(ctx, main, feat))
	list, err = r.WorktreeList(ctx, main)
	require.NoError(t, err)
	for _, w := range list {
		require.NotEqual(t, "feat-x", w.Branch)
	}
}

func TestParseWorktreeList(t *testing.T) {
	t.Parallel()
	buf := []byte("worktree /m\nHEAD aaa\nbranch refs/heads/main\n\nworktree /f\nHEAD bbb\nbranch refs/heads/feat-x\n\n")
	got := parseWorktreeList(buf)
	require.Len(t, got, 2)
	require.Equal(t, "main", got[0].Branch)
	require.Equal(t, "feat-x", got[1].Branch)
}
