package logic

import (
	"context"
	"errors"
	"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 UpdatePlayerServicesLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *UpdatePlayerServicesLogic) UpdatePlayerServices(in *pb.UpdatePlayerServicesReq) (*pb.UpdatePlayerServicesResp, error) {
	update := l.svcCtx.PlayerModelRW.PlayerServices.UpdateOneID(in.Id).
		SetNillablePlayerID(in.PlayerId).
		SetNillableDescription(in.Description).
		SetNillableGameID(in.GameId).
		SetNillableIsActive(in.IsActive).
		SetNillableRankRange(in.RankRange).
		SetNillableTitle(in.Title).
		SetNillableUnit(in.Unit).
		SetAvailability(in.Availability)
	if in.Price != nil {
		price := decimal.NewFromFloat(*in.Price)
		update.SetNillablePrice(&price)
	}
	if in.Rating != nil {
		rating := decimal.NewFromFloat(*in.Rating)
		update.SetNillableRating(&rating)
	}

	_, err := update.Save(l.ctx)
	if err != nil {
		logx.Errorf("failed to update player services: %v", err)
		return nil, errors.New("failed to update player services")
	}
	return &pb.UpdatePlayerServicesResp{}, nil
}
