package usecase

import (
	"context"
	"strings"
	"testing"

	"apps/backend/internal/module/notification/domain"
)

func TestRenderVerifyZhHermes(t *testing.T) {
	s := NewService(Config{
		DevExposeCode: true,
		Brand: domain.Brand{
			Name: "Harbor Desk", Link: "http://127.0.0.1:5173",
			LogoURL: "http://127.0.0.1:5173/brand-mark.svg", Copyright: "© Harbor Desk",
		},
	})
	subj, html, err := s.RenderVerify(domain.TemplateEmailVerify, domain.LangZhTW, domain.VerifyTemplateVars{
		Username: "Daniel", VerifyCode: "123456",
	})
	if err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(subj, "Harbor") {
		t.Fatalf("subject: %s", subj)
	}
	if !strings.Contains(html, "123456") || !strings.Contains(html, "Daniel") {
		t.Fatalf("body missing code/name")
	}
	if !strings.Contains(html, "brand-mark.svg") {
		t.Fatalf("missing logo url")
	}
}

func TestRenderPasswordResetEnHasLinkAndLogo(t *testing.T) {
	s := NewService(Config{
		Brand: domain.Brand{
			Name: "Harbor Desk", Link: "http://127.0.0.1:5173",
			LogoURL: "http://127.0.0.1:5173/brand-mark.svg", Copyright: "© Harbor Desk",
		},
	})
	url := "http://127.0.0.1:5173/reset-password?email=a%40b.com&token=654321"
	subj, html, err := s.RenderVerify(domain.TemplatePasswordReset, "en", domain.VerifyTemplateVars{
		Username: "Daniel", VerifyCode: "654321", ResetURL: url,
	})
	if err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(subj, "Reset") {
		t.Fatalf("en subject: %s", subj)
	}
	if !strings.Contains(html, "654321") || !strings.Contains(html, "reset-password") {
		t.Fatalf("reset mail missing code or link")
	}
	if !strings.Contains(html, "brand-mark.svg") {
		t.Fatalf("missing logo")
	}
	if !strings.Contains(html, "Open reset page") {
		t.Fatalf("missing EN CTA")
	}
}

func TestNormalizeLanguage(t *testing.T) {
	cases := map[string]domain.Language{
		"zh-TW": domain.LangZhTW,
		"zh-tw": domain.LangZhTW,
		"en":    domain.LangEnUS,
		"en-US": domain.LangEnUS,
		"en-us,en;q=0.9": domain.LangEnUS,
		"": domain.LangZhTW,
	}
	for in, want := range cases {
		if got := domain.NormalizeLanguage(in); got != want {
			t.Fatalf("%q → %q want %q", in, got, want)
		}
	}
}

func TestLogDelivery(t *testing.T) {
	s := NewService(Config{})
	err := s.SendEmail(context.Background(), domain.EmailRequest{
		RecipientEmail: "a@b.com",
		Subject:        "t",
		HTMLBody:       "<p>x</p>",
	})
	if err != nil {
		t.Fatal(err)
	}
}
