package logic

import (
	"context"
	"errors"
	"juwan-backend/app/snowflake/rpc/snowflake"

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

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

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

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

// -----------------------players-----------------------
func (l *AddPlayersLogic) AddPlayers(in *pb.AddPlayersReq) (*pb.AddPlayersResp, error) {
	idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{})
	if err != nil {
		logx.Errorf("addPlayerServices err:%v", err)
		return nil, errors.New("create player service id failed")
	}
	creator := l.svcCtx.PlayerModelRW.Players.Create().
		SetID(idResp.Id).
		SetUserID(in.UserId).
		SetStatus(in.Status).
		SetRating(decimal.NewFromFloat(in.Rating)).
		SetGender(in.Gender != 0)
	if in.TotalOrders != 0 {
		creator.SetTotalOrders(int(in.TotalOrders))
	}
	if in.CompletedOrders != 0 {
		creator.SetCompletedOrders(int(in.CompletedOrders))
	}
	if in.ShopId != 0 {
		creator.SetShopID(in.ShopId)
	}
	if len(in.GetTags()) > 0 {
		creator.SetTags(in.GetTags())
	}
	if len(in.GetGames()) > 0 {
		creator.SetGames(in.GetGames())
	}
	_, err = creator.Save(l.ctx)
	if err != nil {
		logx.Errorf("addPlayerServices err:%v", err)
		return nil, errors.New("add player service failed")
	}
	return &pb.AddPlayersResp{}, nil
}
