package services

import (
	"strings"
	"testing"
)

func TestMessageVariablesAreIsolatedPerRecipient(t *testing.T) {
	recipients := []MessageRecipient{
		{Number: "628111111111", Name: "Aisyah", Variables: map[string]string{"paket": "Reguler", "tagihan": "Rp5.000.000"}},
		{Number: "628222222222", Name: "Nadia", Variables: map[string]string{"paket": "Nyaman", "tagihan": "Rp7.000.000"}},
	}
	const template = "Halo {nama}, paket {paket}, tagihan {tagihan}. Nomor {nomor}."
	if err := ValidateMessageRecipients(template, recipients); err != nil {
		t.Fatal(err)
	}
	want := []string{"Halo Aisyah, paket Reguler, tagihan Rp5.000.000. Nomor 628111111111.", "Halo Nadia, paket Nyaman, tagihan Rp7.000.000. Nomor 628222222222."}
	for i, r := range recipients {
		got, err := RenderRecipientMessage(template, r)
		if err != nil || got != want[i] {
			t.Fatalf("recipient %d: %q, %v", i, got, err)
		}
	}
}

func TestMessageVariablesMissingBranchAndInvalidData(t *testing.T) {
	for _, tc := range []struct {
		name, template string
		variables      map[string]string
	}{
		{"unknown", "Tagihan {tagihan}", nil},
		{"blank", "Tagihan {tagihan}", map[string]string{"tagihan": " \n "}},
		{"unchosen_spin", "{Halo|Tagihan {tagihan}}", nil},
		{"reserved", "Halo", map[string]string{"nama": "Override"}},
		{"bad_key", "Halo", map[string]string{"jatuh tempo": "besok"}},
		{"oversized", "Halo", map[string]string{"catatan": strings.Repeat("a", 2001)}},
	} {
		t.Run(tc.name, func(t *testing.T) {
			err := ValidateMessageRecipients(tc.template, []MessageRecipient{{Number: "628111111111", Variables: tc.variables}})
			if err == nil {
				t.Fatal("incomplete or invalid data accepted")
			}
		})
	}
}

func TestMessageVariableValuesStayLiteral(t *testing.T) {
	r := MessageRecipient{Number: "628111111111", Variables: map[string]string{"catatan": "Kode {nomor} / {A|B} / $1\nBaris kedua"}}
	got, err := RenderRecipientMessage("Halo {nama}, {CATATAN}", r)
	if err != nil || got != "Halo kak, Kode {nomor} / {A|B} / $1\nBaris kedua" {
		t.Fatalf("recipient values were interpreted: %q %v", got, err)
	}
}
