// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2

package auth

import (
	"context"
	"errors"
	"fmt"
	"regexp"
	"strconv"
	"time"

	"juwan-backend/app/users/rpc/pb"
	"juwan-backend/app/users/rpc/usercenter"
	"juwan-backend/common/utils/contextj"
	"juwan-backend/common/utils/pwdUtils"

	"juwan-backend/app/users/api/internal/svc"
	"juwan-backend/app/users/api/internal/types"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"k8s.io/apimachinery/pkg/util/json"
)

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

// 用户注册
func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

var usernameRegex = regexp.MustCompile("^[a-zA-Z0-9_]+$")

func (l *RegisterLogic) Register(req *types.RegisterReq) (*types.RegisterResp, string, error) {
	existingUser, err := l.svcCtx.UserRpc.GetUserByUsername(l.ctx, &pb.GetUserByUsernameReq{
		Username: req.Username,
	})
	if len(req.Username) < 3 {
		return nil, "", errors.New("username must be at least 3 characters long")
	}
	if len(req.Username) > 20 {
		return nil, "", errors.New("username must be at most 20 characters long")
	}
	if !usernameRegex.MatchString(req.Username) {
		return nil, "", errors.New("username can only contain letters, numbers, and underscores")
	}
	if err == nil && existingUser != nil {
		return nil, "", errors.New("user already exists")
	}

	hashedPassword, err := pwdUtils.HashPassword(req.Password)
	if err != nil {
		return nil, "", errors.New("hash password failed")
	}

	requestId, err := contextj.RIdFrom(l.ctx)
	logx.Infof("requestId: %s", requestId)
	if err != nil {
		logx.Errorf("contextj.RequestIdFrom failed: %v", err)
		return nil, "", errors.New("contextj.RequestIdFrom failed")
	}

	res, err := l.svcCtx.UserRpc.Register(l.ctx, &usercenter.RegisterReq{
		Username:  req.Username,
		Passwd:    hashedPassword,
		Phone:     req.Username,
		Vcode:     req.Vcode,
		Email:     req.Email,
		RequestId: requestId,
	})
	if err != nil {
		logx.Error("failed to register user: ", err)
		return nil, "", errors.New(fmt.Sprintf("failed to register user: %v", err.Error()))
	}

	userResp, err := l.svcCtx.UserRpc.GetUserByUsername(l.ctx, &pb.GetUserByUsernameReq{
		Username: req.Username,
	})
	if err != nil {
		logx.Errorf("GetUserByUsername err: %v", err)
		return nil, "", errors.New("get user failed")
	}

	user := &types.User{}
	err = copier.Copy(user, userResp.Users)
	if err != nil {
		logx.Errorf("copier.Copy err: %v", err)
		return nil, "", errors.New("copy user failed")
	}
	user.Id = strconv.FormatInt(userResp.Users.Id, 10)
	var verificationStatus map[string]string
	err = json.Unmarshal([]byte(userResp.Users.VerificationStatus), &verificationStatus)
	if err != nil {
		logx.Errorf("json.Unmarshal err: %v", err)
	}
	user.VerifiedRoles = userResp.Users.VerifiedRoles
	user.VerificationStatus = verificationStatus
	user.Role = userResp.Users.CurrentRole
	user.CreatedAt = time.Unix(userResp.Users.CreatedAt, 0).Format(time.DateTime)

	return &types.RegisterResp{
		User: *user,
	}, res.Res, nil
}
