package gitrepo

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

func TestAncestorAndConflict(t *testing.T) {
	if _, err := exec.LookPath("git"); err != nil {
		t.Skip("git ontbreekt")
	}
	dir := t.TempDir()
	git := func(args ...string) {
		t.Helper()
		cmd := exec.Command("git", args...)
		cmd.Dir = dir
		cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.com", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.com")
		if out, err := cmd.CombinedOutput(); err != nil {
			t.Fatalf("git %v: %v\n%s", args, err, out)
		}
	}
	git("init", "-b", "master")
	git("config", "user.email", "t@example.com")
	git("config", "user.name", "t")
	if err := os.WriteFile(filepath.Join(dir, "a.txt"), []byte("a\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	git("add", "a.txt")
	git("commit", "-m", "start")
	git("checkout", "-b", "topic")
	if err := os.WriteFile(filepath.Join(dir, "b.txt"), []byte("b\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	git("add", "b.txt")
	git("commit", "-m", "topic")
	ctx := context.Background()
	if !IsAncestor(ctx, "git", dir, "master", "topic") {
		t.Fatal("master hoort in topic te zitten")
	}
	if IsAncestor(ctx, "git", dir, "topic", "master") {
		t.Fatal("topic zit nog niet in master")
	}
	conflict, err := Conflicts(ctx, "git", dir, "master", "topic")
	if err != nil || conflict {
		t.Fatalf("schone merge: %v %v", conflict, err)
	}
	git("checkout", "master")
	git("merge", "--no-edit", "topic")
	if !IsAncestor(ctx, "git", dir, "topic", "master") {
		t.Fatal("na de merge hoort topic in master te zitten")
	}

	other := t.TempDir()
	gitc := func(args ...string) {
		t.Helper()
		cmd := exec.Command("git", args...)
		cmd.Dir = other
		cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.com", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.com")
		if out, err := cmd.CombinedOutput(); err != nil {
			t.Fatalf("git %v: %v\n%s", args, err, out)
		}
	}
	gitc("init", "-b", "master")
	gitc("config", "user.email", "t@example.com")
	gitc("config", "user.name", "t")
	if err := os.WriteFile(filepath.Join(other, "a.txt"), []byte("a\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	gitc("add", "a.txt")
	gitc("commit", "-m", "start")
	gitc("checkout", "-b", "topic")
	if err := os.WriteFile(filepath.Join(other, "a.txt"), []byte("links\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	gitc("commit", "-am", "links")
	gitc("checkout", "master")
	if err := os.WriteFile(filepath.Join(other, "a.txt"), []byte("rechts\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	gitc("commit", "-am", "rechts")
	conflict, err = Conflicts(ctx, "git", other, "master", "topic")
	if err != nil || !conflict {
		t.Fatalf("conflict verwacht: %v %v", conflict, err)
	}
}
