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

package user

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

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

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

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

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

// 更改当前登录用户信息
func NewUpdateMeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateMeLogic {
	return &UpdateMeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateMeLogic) UpdateMe(req *types.UpdateUserProfileReq) (resp *types.User, err error) {
	userId, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	_, err = l.svcCtx.UserRpc.UpdateUsers(l.ctx, &usercenter.UpdateUsersReq{
		Id:            userId,
		Nickname:      proto_string(req.Nickname),
		Avatar:        proto_string(req.Avatar),
		Bio:           proto_string(req.Bio),
		VerifiedRoles: nil,
	})
	if err != nil {
		return nil, errors.New("update info failed")
	}
	user, err := l.svcCtx.UserRpc.GetUsersById(l.ctx, &usercenter.GetUsersByIdReq{
		Id: userId,
	})
	if err != nil {
		logx.Errorf("UpdateMeLogic.GetUsersById err: %v", err)
		return nil, errors.New("get user failed")
	}

	resp = &types.User{}
	err = converter.StructToStruct(user.Users, resp)
	if err != nil {
		logx.Errorf("struct to user info failed, err:%v.", err)
		return nil, errors.New("get 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
}

func proto_string(s string) *string {
	if strings.TrimSpace(s) == "" {
		return nil
	}
	return &s
}
