package logic

import (
	"context"
	"juwan-backend/app/users/rpc/internal/svc"
	"juwan-backend/app/users/rpc/pb"
	"juwan-backend/pkg/types"

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

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

func NewUpdateUsersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUsersLogic {
	return &UpdateUsersLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateUsersLogic) UpdateUsers(in *pb.UpdateUsersReq) (*pb.UpdateUsersResp, error) {
	updater := l.svcCtx.UsersModelRW.Users.UpdateOneID(in.Id).
		SetNillableNickname(in.Nickname).
		SetNillableAvatar(in.Avatar).
		SetNillableBio(in.Bio).
		SetNillableCurrentRole(in.CurrentRole).
		SetNillablePasswordHash(in.PasswordHash).
		SetNillableIsAdmin(in.IsAdmin)
	if len(in.VerifiedRoles) > 0 {
		verifiedRoles := types.TextArray{Elements: append([]string{}, in.VerifiedRoles...), Valid: true}
		updater.SetVerifiedRoles(verifiedRoles)
	}
	err := updater.Exec(l.ctx)
	if err != nil {
		return nil, err
	}
	return &pb.UpdateUsersResp{}, nil
}
