package services

// Regression tests for the per-draft language column (t-paliad-276).
// The draft's `language` value drives both the placeholder-bag
// language pick (`procedural_event.name` → name_de vs name_en) and the
// template-variant lookup (`{code}.{lang}.docx` fallback chain). These
// tests pin the pure-function pieces — Build wiring needs DB fixtures
// and lives in the handler-layer smoke path.

import (
	"strings"
	"testing"

	"github.com/google/uuid"

	"mgit.msbls.de/m/paliad/internal/models"
)

func TestNormalizeDraftLanguage(t *testing.T) {
	t.Parallel()
	cases := []struct {
		in   string
		want string
	}{
		{"de", "de"},
		{"DE", "de"},
		{" de ", "de"},
		{"en", "en"},
		{"EN", "en"},
		{"  en  ", "en"},
		{"fr", "de"},  // unknown collapses to de (the CHECK-allowed default)
		{"", "de"},
		{"english", "de"}, // strict — only the canonical two-letter code is accepted
	}
	for _, c := range cases {
		if got := normalizeDraftLanguage(c.in); got != c.want {
			t.Errorf("normalizeDraftLanguage(%q) = %q, want %q", c.in, got, c.want)
		}
	}
}

// The placeholder bag picks the language-matched value for the
// canonical (procedural_event.name) and legacy (rule.name) keys based
// on the lang argument. This pins the wiring used by Build when a
// draft's language overrides the user's UI lang (t-paliad-276).
func TestAddRuleVars_LanguageSelectsMatchedName(t *testing.T) {
	t.Parallel()
	code := "de.inf.lg.erwidg"
	rule := &models.DeadlineRule{
		ID:             uuid.New(),
		SubmissionCode: &code,
		Name:           "Klageerwiderung",
		NameEN:         "Statement of Defence",
	}
	for _, lang := range []string{"de", "en"} {
		bag := PlaceholderMap{}
		addRuleVars(bag, rule, lang)
		want := rule.Name
		if strings.EqualFold(lang, "en") {
			want = rule.NameEN
		}
		if got := bag["procedural_event.name"]; got != want {
			t.Errorf("lang=%s: procedural_event.name = %q, want %q", lang, got, want)
		}
		if got := bag["rule.name"]; got != want {
			t.Errorf("lang=%s: rule.name = %q, want %q (legacy alias must mirror canonical)", lang, got, want)
		}
		// The explicit *_de / *_en keys never change — both are always
		// emitted so a template can pin one regardless of the draft's
		// language. Regression guard against accidentally
		// language-gating the explicit variants.
		if bag["procedural_event.name_de"] != rule.Name {
			t.Errorf("lang=%s: procedural_event.name_de = %q, want %q", lang, bag["procedural_event.name_de"], rule.Name)
		}
		if bag["procedural_event.name_en"] != rule.NameEN {
			t.Errorf("lang=%s: procedural_event.name_en = %q, want %q", lang, bag["procedural_event.name_en"], rule.NameEN)
		}
	}
}
