package git

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

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

func TestListTrackedFiles(t *testing.T) {
	gitAvailable(t)
	dir := t.TempDir()
	mustGit(t, dir, "init", "-b", "main")
	mustGit(t, dir, "config", "user.email", "test@example.com")
	mustGit(t, dir, "config", "user.name", "Test")
	require.NoError(t, os.WriteFile(filepath.Join(dir, "a.go"), []byte("package a\n"), 0o644))
	require.NoError(t, os.MkdirAll(filepath.Join(dir, "sub"), 0o755))
	require.NoError(t, os.WriteFile(filepath.Join(dir, "sub", "b.txt"), []byte("b\n"), 0o644))
	// Untracked + ignored files must NOT appear.
	require.NoError(t, os.WriteFile(filepath.Join(dir, ".gitignore"), []byte("ignored.txt\n"), 0o644))
	require.NoError(t, os.WriteFile(filepath.Join(dir, "ignored.txt"), []byte("x\n"), 0o644))
	require.NoError(t, os.WriteFile(filepath.Join(dir, "untracked.txt"), []byte("y\n"), 0o644))
	mustGit(t, dir, "add", "a.go", "sub/b.txt", ".gitignore")
	mustGit(t, dir, "commit", "-m", "init")

	r := newTestRunner(t)
	files, err := r.ListTrackedFiles(context.Background(), dir)
	require.NoError(t, err)
	sort.Strings(files)
	require.Equal(t, []string{".gitignore", "a.go", "sub/b.txt"}, files)
}

func TestDiffStat(t *testing.T) {
	gitAvailable(t)
	dir := t.TempDir()
	mustGit(t, dir, "init", "-b", "main")
	mustGit(t, dir, "config", "user.email", "test@example.com")
	mustGit(t, dir, "config", "user.name", "Test")
	require.NoError(t, os.WriteFile(filepath.Join(dir, "f.go"), []byte("package f\n\nfunc F() {}\n"), 0o644))
	mustGit(t, dir, "add", "f.go")
	mustGit(t, dir, "commit", "-m", "add F")

	r := newTestRunner(t)
	// HEAD resolves the just-made commit.
	commits, err := r.Log(context.Background(), dir, 1)
	require.NoError(t, err)
	require.Len(t, commits, 1)

	stat, err := r.DiffStat(context.Background(), dir, commits[0].Hash)
	require.NoError(t, err)
	require.Contains(t, stat, "f.go")
	require.Contains(t, stat, "add F") // subject from --format
}
