from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Transfer, TransferEvent


@receiver(post_save, sender=Transfer)
def create_transfer_event_on_status_change(sender, instance, created, **kwargs):
    """
    Create a transfer event when transfer is created
    Additional events for status changes are created in the model methods
    """
    if created:
        # Create initial event
        TransferEvent.objects.create(
            transfer=instance,
            event_type='CREATED',
            user=instance.requested_by,
            notes=f"Transfer created from {instance.source_location.name} to {instance.destination_location.name}",
            metadata={
                'priority': instance.priority,
                'items_count': instance.items.count() if hasattr(instance, 'items') else 0
            }
        )


# Optional: Add notification signals here
# Example: Send email/push notification when transfer is approved, shipped, etc.

@receiver(post_save, sender=Transfer)
def send_transfer_notifications(sender, instance, created, **kwargs):
    """
    Send notifications based on transfer status changes
    This is a placeholder - implement your notification logic here
    """
    # Example implementation:
    # if instance.status == 'APPROVED' and instance.approved_date:
    #     send_email_notification(
    #         to=instance.requested_by.email,
    #         subject=f"Transfer {instance.transfer_number} Approved",
    #         message=f"Your transfer request has been approved."
    #     )
    #
    # if instance.status == 'IN_TRANSIT' and instance.shipped_date:
    #     send_email_notification(
    #         to=instance.destination_location.manager_email,
    #         subject=f"Transfer {instance.transfer_number} In Transit",
    #         message=f"Transfer is on the way to {instance.destination_location.name}"
    #     )
    pass