"""
Django signals for the accounting app.

Auto-creates a Receipt (with PDF) whenever an AccountTransaction is saved
for the first time.

Failure policy
--------------
- Receipt *row* creation (number generation + DB insert): NOT caught here.
  Any error propagates and rolls back the enclosing transaction save.
  A transaction without a receipt number is unacceptable.
- PDF generation: caught and logged (non-fatal).  The PDF is regenerated
  on demand the first time someone hits the download endpoint, so a
  transient reportlab error should not prevent the transaction being recorded.
"""

import logging

from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.files.base import ContentFile

from .models import AccountTransaction, Receipt

logger = logging.getLogger(__name__)


# The create_receipt_on_transaction_save signal was removed because receipts are now created
# explicitly via the ReceiptViewSet, allowing multiple transactions per receipt.


from django.db.models.signals import post_delete

@receiver(post_delete, sender=AccountTransaction)
def handle_transaction_delete(sender, instance, **kwargs):
    """
    Recalculates a member's financial rollups if an AccountTransaction
    is hard deleted (e.g. from tests or Django Admin).
    """
    if instance.member:
        from .utils import recalculate_member_financials
        recalculate_member_financials(instance.member, instance.transaction_date)
