package cispec

import (
	"encoding/json"
	"strings"
	"testing"

	"gitlab.com/Timfa/bluegit/internal/i18n"
	"gitlab.com/Timfa/bluegit/internal/images"
)

func TestDocumentListsSpecAndPresets(t *testing.T) {
	doc := Build(i18n.EN, nil)
	raw := Marshal(doc)
	var again Doc
	if err := json.Unmarshal(raw, &again); err != nil {
		t.Fatal(err)
	}
	if string(Marshal(again)) != string(raw) {
		t.Fatal("marshal loopt uiteen")
	}
	names := map[string]bool{}
	for _, sec := range doc.Sections {
		for _, item := range sec.Items {
			names[item.Name] = true
			if item.Summary == "" || item.Summary == "info.kw."+strings.ReplaceAll(item.Name, ".", "") {
				t.Fatalf("lege tekst %s", item.Name)
			}
		}
	}
	for _, name := range []string{"stages", "workflow", "rules", "retry", "parallel", "services", "environment", "interruptible", "artifacts", "cache", "needs", "extends", "if", "changes", "exists"} {
		if !names[name] {
			t.Fatalf("mist %s", name)
		}
	}
	var presets []Preset
	var variables []Variable
	for _, sec := range doc.Sections {
		presets = append(presets, sec.Presets...)
		variables = append(variables, sec.Variables...)
	}
	if len(presets) != 7 || presets[0].Name != "bluegit/base" || presets[0].From != "alpine:3.20" || presets[0].Mode != "dockerfile" {
		t.Fatalf("presets %+v", presets)
	}
	found := map[string]Variable{}
	for _, v := range variables {
		found[v.Name] = v
	}
	if found["CI_JOB_TOKEN"].Scope != "container" || found["CI_PIPELINE_ID"].Scope != "both" || found["CI_MERGE_REQUEST_IID"].Scope != "mr" {
		t.Fatalf("scopes %+v %+v %+v", found["CI_JOB_TOKEN"], found["CI_PIPELINE_ID"], found["CI_MERGE_REQUEST_IID"])
	}
	nl := Build(i18n.NL, nil)
	if nl.Sections[0].Title == doc.Sections[0].Title && nl.Sections[0].Items[0].Summary == doc.Sections[0].Items[0].Summary {
		t.Fatal("Nederlands valt terug op Engels")
	}
	cu := Build(i18n.Cuneiform, images.Builtin())
	if cu.Sections[0].Items[0].Name != "stages" {
		t.Fatal(cu.Sections[0].Items[0].Name)
	}
	for _, r := range cu.Sections[0].Title {
		if r == ' ' {
			continue
		}
		if r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' {
			t.Fatalf("Latijn in de titel %s", cu.Sections[0].Title)
		}
	}
}
