package worker

import (
	"encoding/json"
	"testing"
)

func TestBuildWelcomeEmailPayload_RoundTrip(t *testing.T) {
	data, err := BuildWelcomeEmailPayload("a@b.com", "Alice", "CODE123")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	var p WelcomeEmailPayload
	if err := json.Unmarshal(data, &p); err != nil {
		t.Fatalf("unmarshal: %v", err)
	}
	if p.To != "a@b.com" || p.FirstName != "Alice" || p.ConfirmationCode != "CODE123" {
		t.Errorf("got %+v", p)
	}
}

func TestBuildVerificationEmailPayload_RoundTrip(t *testing.T) {
	data, err := BuildVerificationEmailPayload("b@c.com", "Bob", "VERIFY456")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	var p VerificationEmailPayload
	if err := json.Unmarshal(data, &p); err != nil {
		t.Fatalf("unmarshal: %v", err)
	}
	if p.To != "b@c.com" || p.FirstName != "Bob" || p.Code != "VERIFY456" {
		t.Errorf("got %+v", p)
	}
}

func TestBuildPasswordResetEmailPayload_RoundTrip(t *testing.T) {
	data, err := BuildPasswordResetEmailPayload("c@d.com", "Carol", "RST789", "token-abc")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	var p PasswordResetEmailPayload
	if err := json.Unmarshal(data, &p); err != nil {
		t.Fatalf("unmarshal: %v", err)
	}
	if p.To != "c@d.com" || p.FirstName != "Carol" || p.Code != "RST789" || p.ResetToken != "token-abc" {
		t.Errorf("got %+v", p)
	}
}

func TestBuildPasswordChangedEmailPayload_RoundTrip(t *testing.T) {
	data, err := BuildPasswordChangedEmailPayload("d@e.com", "Dave")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	var p EmailPayload
	if err := json.Unmarshal(data, &p); err != nil {
		t.Fatalf("unmarshal: %v", err)
	}
	if p.To != "d@e.com" || p.FirstName != "Dave" {
		t.Errorf("got %+v", p)
	}
}

func TestBuildWelcomeEmailPayload_Fields(t *testing.T) {
	data, err := BuildWelcomeEmailPayload("test@example.com", "Test", "ABC")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	// Verify raw JSON contains expected keys
	var raw map[string]interface{}
	if err := json.Unmarshal(data, &raw); err != nil {
		t.Fatalf("unmarshal: %v", err)
	}
	for _, key := range []string{"to", "first_name", "confirmation_code"} {
		if _, ok := raw[key]; !ok {
			t.Errorf("missing key %q in payload JSON", key)
		}
	}
}
