# =======================
# AUTO-STATUS UPDATE SIGNAL for OVERPAID LOANS
# Add this to loans/models.py after the Loan model definition
# =======================

from django.db.models.signals import pre_save
from django.dispatch import receiver

@receiver(pre_save, sender=Loan)
def auto_update_paid_status(sender, instance, **kwargs):
    """
    Automatically update loan status to 'paid' when outstanding amount is <= 0
    Only applies to active loans that are not rolled over
    """
    # Only check for existing loans (not new ones)
    if instance.pk:
        # Don't change status if already rolled over or already paid
        if instance.status in ['rolled_over', 'paid']:
            return
        
        # Check if loan is fully paid (outstanding <= 0)
        try:
            outstanding = instance.outstanding_amount
            if outstanding <= 0 and instance.status == 'active':
                instance.status = 'paid'
                # Note: This will be saved automatically by the pre_save signal
        except:
            # If there's any error calculating outstanding, don't change status
            pass
