# finance/signals.py
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from .models import Invoice, Payment
from .utils import generate_invoice_number

@receiver(pre_save, sender=Invoice)
def set_invoice_number(sender, instance, **kwargs):
    """Generate invoice number before saving"""
    if not instance.invoice_number:
        from .utils import generate_invoice_number
        instance.invoice_number = generate_invoice_number()

@receiver(post_save, sender=Payment)
def update_invoice_on_payment(sender, instance, created, **kwargs):
    """Update invoice amount_paid when payment is saved"""
    if instance.status == 'completed':
        invoice = instance.invoice
        from django.db.models import Sum
        total_paid = Payment.objects.filter(
            invoice=invoice,
            status='completed'
        ).aggregate(Sum('amount'))['amount__sum'] or 0
        invoice.amount_paid = total_paid
        invoice.save()