import logging

from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver

from account.models import User, ReferralRelationship, BonusProgramTransaction

logger = logging.getLogger(__name__)


@receiver(post_save, sender=User)
def handle_user_save(sender, instance: User, created, **kwargs):
    pass


@receiver(post_save, sender=ReferralRelationship)
def handle_invitation_save(sender, instance: ReferralRelationship, created, **kwargs):
    if created:
        logger.info(f"User {instance.inviter_id} invited {instance.invited_id}")
        # TODO: notify about invitation


@receiver(post_save, sender=BonusProgramTransaction)
@receiver(post_delete, sender=BonusProgramTransaction)
def handle_bonus_transaction_savedelete(sender, instance: BonusProgramTransaction, **kwargs):
    # Recalculate user's balance
    if instance.user is not None:
        instance.user.recalculate_balance()

