package logic

import (
	"fusenapi/utils/auth"
	"fusenapi/utils/basic"
	"time"

	"context"

	"fusenapi/server/auth/internal/svc"
	"fusenapi/server/auth/internal/types"

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

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

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

// 处理进入前逻辑w,r
// func (l *UserRegisterLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }

func (l *UserRegisterLogic) UserRegister(req *types.RequestUserRegister, userinfo *auth.UserInfo) (resp *basic.Response) {
	// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
	// userinfo 传入值时, 一定不为null

	// 邮箱验证格式错误
	if !auth.ValidateEmail(req.Email) {
		return resp.SetStatus(basic.CodeOAuthEmailErr)
	}

	token := &auth.RegisterToken{
		OperateType: auth.OpTypeRegister,
		Id:          0,
		GuestId:     userinfo.GuestId,
		Wid:         req.Wid,
		Email:       req.Email,
		Password:    req.Password,
		Platform:    "fusen",
		TraceId:     uuid.NewString(),
		CreateAt:    time.Now(),
	}

	clurl, err := l.svcCtx.RegisterTokenManger.Generate(token)
	if err != nil {
		logx.Error(err)
		return resp.SetStatus(basic.CodeOAuthRegisterTokenErr)
	}

	// 进入发送邮箱的系统
	EmailManager.EmailTasks <- &EmailFormat{
		TargetEmail:      req.Email,
		CompanyName:      "fusen",
		ConfirmationLink: clurl,
		SenderName:       "support@fusenpack.com",
		SenderTitle:      "register-valid",
	} // email进入队

	return resp.SetStatus(basic.CodeOK)
}

// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *UserRegisterLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)
// }