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

package auth

import (
	"context"
	"errors"
	"strconv"
	"time"

	"juwan-backend/app/users/rpc/usercenter"

	"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 LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 用户登录
func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (*types.LoginResp, string, error) {
	// todo: add your logic here and delete this line
	if len(req.Username) < 3 || len(req.Password) < 8 || len(req.Password) > 20 {
		return nil, "", errors.New("the information is illegal")
	}

	res, err := l.svcCtx.UserRpc.Login(l.ctx, &usercenter.LoginReq{
		Username: req.Username,
		Passwd:   req.Password,
	})
	logx.Infof("res:%v", res)
	if err != nil {
		logx.Errorf("rpc login err: %v", err)
		return nil, "", errors.New("login fail")
	}

	if res == nil || res.Id <= 0 || res.Username == "" || res.Token == "" {
		logx.Errorf("rpc login returned empty payload, username=%s, resp=%+v", req.Username, res)
		return nil, "", errors.New("login fail")
	}

	userResp, err := l.svcCtx.UserRpc.GetUsersById(l.ctx, &usercenter.GetUsersByIdReq{Id: res.Id})
	if err != nil {
		logx.Errorf("GetUsersById 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.LoginResp{
		User: *user,
	}, res.Token, nil
}
