package logic

import (
	"context"
	"errors"
	"juwan-backend/app/player/rpc/internal/models/players"

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

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

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

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

func (l *GetPlayersByIdLogic) GetPlayersById(in *pb.GetPlayersByIdReq) (*pb.GetPlayersByIdResp, error) {
	player, err := l.svcCtx.PlayerModelRO.Players.Query().Where(players.IDEQ(in.Id)).First(l.ctx)
	if err != nil {
		logx.WithContext(l.ctx).Errorf("GetPlayersByIdLogic err: %v", err)
		return nil, errors.New("get players by id failed")
	}

	pbPlayer := pb.Players{
		Id:              player.ID,
		UserId:          player.UserID,
		Status:          player.Status,
		Gender:          player.Gender,
		Rating:          player.Rating.InexactFloat64(),
		TotalOrders:     int64(player.TotalOrders),
		CompletedOrders: int64(player.CompletedOrders),
		Tags:            player.Tags,
		Games:           []int64(player.Games),
		CreatedAt:       player.CreatedAt.Unix(),
		UpdatedAt:       player.UpdatedAt.Unix(),
	}
	if player.ShopID != nil {
		pbPlayer.ShopId = *player.ShopID
	}

	return &pb.GetPlayersByIdResp{Players: &pbPlayer}, nil
}
