from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from .models import Booking
# We need to import BackToBase model. 
# To avoid potential circular imports if BackToBase imports Booking directly, use apps.get_model
from django.apps import apps

@receiver(pre_save, sender=Booking)
def capture_old_status(sender, instance, **kwargs):
    if instance.pk:
        try:
            old_instance = sender.objects.get(pk=instance.pk)
            instance._old_status = old_instance.booking_status
            instance._old_rider_id = old_instance.rider_id
        except sender.DoesNotExist:
            instance._old_status = None
            instance._old_rider_id = None
    else:
        instance._old_status = None
        instance._old_rider_id = None

from django.utils import timezone

@receiver(post_save, sender=Booking)
def handle_booking_updates(sender, instance, created, **kwargs):
    if created:
        return

    old_status = getattr(instance, '_old_status', None)
    new_status = instance.booking_status
    
    old_rider_id = getattr(instance, '_old_rider_id', None)
    new_rider_id = instance.rider_id

    BackToBase = apps.get_model('back_to_base', 'BackToBase')

    # Case 1: Status changed TO 'back_to_base'
    if old_status != 'back_to_base' and new_status == 'back_to_base':
        # Check if there is already an active (unresolved) entry
        if not BackToBase.objects.filter(booking=instance, is_resolved=False).exists():
            BackToBase.objects.create(
                booking=instance,
                rider=instance.rider,
                customer=instance.user,
                reason="Status updated to Back to Base"
            )

    # Case 2: Status changed TO 'completed' (Delivered)
    elif new_status == 'completed':
        # Mark all active entries as resolved
        active_entries = BackToBase.objects.filter(booking=instance, is_resolved=False)
        if active_entries.exists():
            active_entries.update(is_resolved=True, resolved_at=timezone.now())

    # Case 3: Rider changed
    if old_rider_id != new_rider_id:
        # Update rider for all ACTIVE (unresolved) BackToBase entries
        # We assume that if the booking is reassigned, the responsibility for the issue also moves.
        active_entries = BackToBase.objects.filter(booking=instance, is_resolved=False)
        if active_entries.exists():
            active_entries.update(rider_id=new_rider_id)
