package wallet

import (
	"context"
	"hyapp/pkg/appcode"
	"hyapp/pkg/xerr"
	"hyapp/services/wallet-service/internal/domain/ledger"
	"strings"
)

// ApplyGameCoinChange 是游戏平台唯一的 COIN 改账入口，方向由 op_type 控制。
func (s *Service) ApplyGameCoinChange(ctx context.Context, command ledger.GameCoinChangeCommand) (ledger.GameCoinChangeReceipt, error) {
	if command.CommandID == "" || command.UserID <= 0 || command.PlatformCode == "" || command.GameID == "" || command.ProviderOrderID == "" {
		return ledger.GameCoinChangeReceipt{}, xerr.New(xerr.InvalidArgument, "game coin command is incomplete")
	}
	command.OpType = ledger.NormalizeGameOpType(command.OpType)
	if command.OpType == "" {
		return ledger.GameCoinChangeReceipt{}, xerr.New(xerr.InvalidArgument, "game op_type is invalid")
	}
	if command.CoinAmount <= 0 {
		return ledger.GameCoinChangeReceipt{}, xerr.New(xerr.InvalidArgument, "coin_amount must be positive")
	}
	command.RequestHash = strings.TrimSpace(command.RequestHash)
	if command.RequestHash == "" {
		return ledger.GameCoinChangeReceipt{}, xerr.New(xerr.InvalidArgument, "request_hash is required")
	}
	if s.repository == nil {
		return ledger.GameCoinChangeReceipt{}, xerr.New(xerr.Unavailable, "wallet repository is not configured")
	}
	command.AppCode = appcode.Normalize(command.AppCode)
	command.PlatformCode = strings.TrimSpace(command.PlatformCode)
	command.GameID = strings.TrimSpace(command.GameID)
	command.ProviderOrderID = strings.TrimSpace(command.ProviderOrderID)
	command.ProviderRoundID = strings.TrimSpace(command.ProviderRoundID)
	command.RoomID = strings.TrimSpace(command.RoomID)
	ctx = appcode.WithContext(ctx, command.AppCode)

	return s.repository.ApplyGameCoinChange(ctx, command)
}
