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 GetUserByUsernameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *GetUserByUsernameLogic) GetUserByUsername(in *pb.GetUserByUsernameReq) (*pb.GetUserByUsernameResp, error) {
	user, err := l.svcCtx.UsersModelRO.Users.Query().Where(users.UsernameEQ(in.Username)).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")
	}

	pbUser := &pb.Users{
		Id:                 user.ID,
		Username:           user.Username,
		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(),
	}

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