package logic

import (
	"context"
	"errors"
	"juwan-backend/app/player/rpc/internal/models"
	"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"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

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

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

func (l *GetPlayerByUserIdLogic) GetPlayerByUserId(in *pb.SearchPlayersReq) (*pb.GetPlayersByIdResp, error) {
	if in.UserId == nil {
		return nil, errors.New("user id is required")
	}

	player, err := l.svcCtx.PlayerModelRO.Players.Query().Where(players.UserIDEQ(in.GetUserId())).First(l.ctx)
	if err != nil {
		if models.IsNotFound(err) {
			return nil, status.Error(codes.NotFound, "player not found")
		}
		logx.WithContext(l.ctx).Errorf("GetPlayerByUserIdLogic err: %v", err)
		return nil, errors.New("get player by user 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
}
