package gitrepo

import (
	"strconv"
	"strings"
	"testing"
)

func TestParseDiffAndSuggestion(t *testing.T) {
	raw := "" +
		"diff --git a/hello.txt b/hello.txt\n" +
		"--- a/hello.txt\n" +
		"+++ b/hello.txt\n" +
		"@@ -1,3 +1,4 @@\n" +
		" alpha\n" +
		"-beta\n" +
		"+BETA\n" +
		"+extra\n" +
		" gamma\n"
	files := ParseDiff(raw)
	if len(files) != 1 || files[0].Path != "hello.txt" {
		t.Fatalf("%+v", files)
	}
	var news []int
	for _, ln := range files[0].Lines {
		if ln.New > 0 {
			news = append(news, ln.New)
			if ln.New == 2 && (ln.Kind != "add" || ln.Text != "BETA") {
				t.Fatalf("regel 2 %+v", ln)
			}
		}
		if ln.Kind == "del" && (ln.New != 0 || ln.Text != "beta") {
			t.Fatalf("verwijderd %+v", ln)
		}
	}
	gotNums := make([]string, len(news))
	for i, n := range news {
		gotNums[i] = strconv.Itoa(n)
	}
	if strings.Join(gotNums, ",") != "1,2,3,4" {
		t.Fatalf("nieuwe regels %v", news)
	}
	body := "zie\n\n```suggestion\nbeta\nextra\n```\n"
	got, ok := ParseSuggestion(body)
	if !ok || got != "beta\nextra" {
		t.Fatalf("%q %v", got, ok)
	}
	if _, ok := ParseSuggestion("alleen tekst"); ok {
		t.Fatal("geen blok")
	}
}

func TestApplySuggestions(t *testing.T) {
	files := map[string]string{"hello.txt": "alpha\nbeta\ngamma\n"}
	out, err := ApplySuggestions(files, []SuggestionEdit{{
		Path: "hello.txt", Start: 2, End: 2, Base: "beta", Replacement: "BETA",
	}})
	if err != nil || out["hello.txt"] != "alpha\nBETA\ngamma\n" {
		t.Fatalf("%q %v", out["hello.txt"], err)
	}
	if _, err := ApplySuggestions(files, []SuggestionEdit{{
		Path: "hello.txt", Start: 2, End: 2, Base: "oud", Replacement: "BETA",
	}}); err == nil || !strings.Contains(err.Error(), "hello.txt:2-2") {
		t.Fatal(err)
	}
	if _, err := ApplySuggestions(files, []SuggestionEdit{
		{Path: "hello.txt", Start: 1, End: 2, Base: "alpha\nbeta", Replacement: "a"},
		{Path: "hello.txt", Start: 2, End: 3, Base: "beta\ngamma", Replacement: "b"},
	}); err == nil || !strings.Contains(err.Error(), "overlap") {
		t.Fatal(err)
	}
	two, err := ApplySuggestions(files, []SuggestionEdit{
		{Path: "hello.txt", Start: 1, End: 1, Base: "alpha", Replacement: "ALPHA"},
		{Path: "hello.txt", Start: 3, End: 3, Base: "gamma", Replacement: "GAMMA"},
	})
	if err != nil || two["hello.txt"] != "ALPHA\nbeta\nGAMMA\n" {
		t.Fatalf("%q %v", two["hello.txt"], err)
	}
	if _, err := ApplySuggestions(files, []SuggestionEdit{{
		Path: "hello.txt", Start: 2, End: 2, Base: "beta", Replacement: "beta",
	}}); err == nil {
		t.Fatal("lege wijziging")
	}
}
