from .models import Wallet, Transaction


def get_or_create_wallet(user):
    wallet, _ = Wallet.objects.get_or_create(user=user)
    return wallet


def award_points(user, amount, tx_type, description=""):
    """Award (or deduct) points and log the transaction."""
    wallet = get_or_create_wallet(user)
    wallet.balance = max(0, wallet.balance + amount)
    wallet.save(update_fields=["balance"])
    Transaction.objects.create(wallet=wallet, amount=amount, tx_type=tx_type, description=description)
    return wallet
