package gitrepo

import (
	"context"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"
	"time"
)

func TestMaintenanceArgsNeverPruneNow(t *testing.T) {
	for _, args := range [][]string{MaintenanceArgs(), GCAutoArgs()} {
		joined := strings.Join(args, " ")
		if strings.Contains(joined, "--prune=now") || strings.Contains(joined, "prune=now") {
			t.Fatalf("onderhoud mag nooit --prune=now gebruiken: %s", joined)
		}
	}
}

func TestMaintainKeepsReachableObjects(t *testing.T) {
	bare, work := testRepo(t)
	sha := gitSHA(t, bare, "refs/heads/master")
	// Een paar losse objecten zodat gc iets te doen heeft, zonder
	// onbereikbare refs te willen wissen.
	if err := os.WriteFile(filepath.Join(work, "g"), []byte("meer\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	gitOK(t, work, "add", "g")
	gitOK(t, work, "commit", "-qm", "meer")
	gitOK(t, work, "push", "-q", "origin", "master")
	head := gitSHA(t, bare, "refs/heads/master")

	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	res := Maintain(ctx, "git", bare)
	if !res.OK {
		t.Fatalf("maintain: ok=false err=%s out=%s", res.Err, res.Output)
	}
	if got := gitSHA(t, bare, "refs/heads/master"); got != head {
		t.Fatalf("head veranderde: %s -> %s", head, got)
	}
	if err := exec.Command("git", "-C", bare, "cat-file", "-e", sha).Run(); err != nil {
		t.Fatalf("bereikbaar object %s is weg: %v", sha, err)
	}
	if err := exec.Command("git", "-C", bare, "cat-file", "-e", head).Run(); err != nil {
		t.Fatalf("nieuwe head %s is weg: %v", head, err)
	}
}

func TestMaintainMissingDirIsSkipped(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	res := Maintain(ctx, "git", filepath.Join(t.TempDir(), "ontbreekt.git"))
	if res.OK {
		t.Fatal("ontbrekende repo zou moeten falen (en overgeslagen worden)")
	}
	if res.Err == "" {
		t.Fatal("verwacht een fouttekst")
	}
}

func TestMaintainEmptyPathFails(t *testing.T) {
	res := Maintain(context.Background(), "git", "")
	if res.OK || res.Err == "" {
		t.Fatalf("leeg pad moet falen, kreeg %+v", res)
	}
}
