package logic

import (
	"context"
	"encoding/json"
	"errors"
	"juwan-backend/app/users/rpc/internal/models/users"

	"juwan-backend/app/users/rpc/internal/svc"
	"juwan-backend/app/users/rpc/pb"

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

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

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

func (l *GetUsersByIdLogic) GetUsersById(in *pb.GetUsersByIdReq) (*pb.GetUsersByIdResp, error) {
	// todo: add your logic here and delete this line
	//user, err := l.svcCtx.UsersModelRO.FindOne(l.ctx, in.Id)
	user, err := l.svcCtx.UsersModelRO.Users.Query().Where(users.IDEQ(in.Id)).First(l.ctx)
	if err != nil {
		return nil, err
	}

	verificationStatus, err := json.Marshal(user.VerificationStatus)
	if err != nil {
		logx.Errorf("json marshal verification status failed: %v", err)
		return nil, errors.New("marshal verification status failed")
	}

	logx.Debugf("Users data: %+v", user)
	logx.Debugf("verified_role: %+v", user.VerifiedRoles)
	pbUser := &pb.Users{
		Id:                 user.ID,
		Username:           user.Username,
		PasswordHash:       "",
		Phone:              "",
		Email:              "",
		Nickname:           user.Nickname,
		Avatar:             user.Avatar,
		Bio:                user.Bio,
		CurrentRole:        user.CurrentRole,
		VerifiedRoles:      user.VerifiedRoles.Elements,
		VerificationStatus: string(verificationStatus),
		IsAdmin:            user.IsAdmin,
		CreatedAt:          user.CreatedAt.Unix(),
		UpdatedAt:          user.UpdatedAt.Unix(),
		DeletedAt:          user.DeletedAt.Unix(),
	}
	logx.Debugf("pb users data: %+v", pbUser)

	return &pb.GetUsersByIdResp{Users: pbUser}, nil
}
