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

package user

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

	"juwan-backend/app/users/api/internal/svc"
	"juwan-backend/app/users/api/internal/types"
	"juwan-backend/app/users/rpc/usercenter"
	"juwan-backend/common/utils/contextj"

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

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

// 获取当前登录用户信息
func NewGetMeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMeLogic {
	return &GetMeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetMeLogic) GetMe() (resp *types.User, err error) {
	userId, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		logx.Errorf("get user id from context: %v", err)
		return nil, errors.New("illegal user")
	}

	user, err := l.svcCtx.UserRpc.GetUsersById(l.ctx, &usercenter.GetUsersByIdReq{
		Id: userId,
	})
	if err != nil {
		logx.Errorf("GetMeLogic.GetUsersById err: %v", err)
		return nil, errors.New("get user failed")
	}
	logx.Debugf("get user resp: %+v", user)

	resp = &types.User{}

	err = copier.Copy(&resp, user.Users)
	if err != nil {
		logx.Errorf("copier.Copy err: %v", err)
		return nil, errors.New("copy user failed")
	}

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