package auth

import (
	"context"
	"strings"

	"apps/backend/internal/middleware"
	notifDomain "apps/backend/internal/module/notification/domain"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendEmailCodeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSendEmailCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendEmailCodeLogic {
	return &SendEmailCodeLogic{Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}

// SendEmailCode 產生驗證碼 → hermes 多語模板 → 寄信。不回傳驗證碼給前端。
func (l *SendEmailCodeLogic) SendEmailCode() (resp *types.AuthSendCodeData, err error) {
	uid, _ := middleware.UIDFrom(l.ctx)
	code, err := l.svcCtx.Auth.SendEmailCode(l.ctx, uid)
	if err != nil {
		return nil, err
	}

	m, err := l.svcCtx.Members.FindByUID(l.ctx, uid)
	if err != nil {
		return nil, err
	}
	to := strings.TrimSpace(m.Email)
	if to == "" {
		return &types.AuthSendCodeData{Ok: true, Message: "verification code issued"}, nil
	}

	name := m.DisplayName
	if name == "" {
		name = strings.Split(to, "@")[0]
	}
	lang := notifDomain.NormalizeLanguage(m.PreferredLanguage)

	subject, html, err := l.svcCtx.Notification.RenderVerify(
		notifDomain.TemplateEmailVerify,
		lang,
		notifDomain.VerifyTemplateVars{Username: name, VerifyCode: code},
	)
	if err != nil {
		l.Errorf("render email verify template: %v", err)
		return nil, err
	}

	if err := l.svcCtx.Notification.SendEmail(l.ctx, notifDomain.EmailRequest{
		RecipientEmail: to,
		SenderEmail:    l.svcCtx.Notification.SenderFrom(),
		Subject:        subject,
		HTMLBody:       html,
	}); err != nil {
		l.Errorf("send email verify to %s: %v", to, err)
		return nil, err
	}

	return &types.AuthSendCodeData{
		Ok:      true,
		Message: "verification code sent",
	}, nil
}
