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

package user

import (
	"context"
	"errors"
	"strconv"

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

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

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

// 获取用户信息
func NewGetUserInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserInfoLogic {
	return &GetUserInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetUserInfoLogic) GetUserInfo(req *types.GetUserReq) (resp types.User, err error) {
	targetId, err := strconv.ParseInt(req.Id, 10, 64)
	if err != nil {
		return types.User{}, errors.New("invalid user id")
	}

	pbUser, err := l.svcCtx.UserRpc.GetUsersById(l.ctx, &usercenter.GetUsersByIdReq{
		Id: targetId,
	})
	if err != nil {
		return types.User{}, errors.New("failed to get user info by userid")
	}

	user := types.User{}
	err = copier.Copy(&user, &pbUser.Users)
	if err != nil {
		logx.Errorf("struct to user info failed, err:%v.", err)
		return types.User{}, errors.New("failed to get user info by userid")
	}
	user.Id = strconv.FormatInt(pbUser.Users.Id, 10)
	user.Role = pbUser.Users.CurrentRole

	return user, nil
}
