"""
Public API Signals

Signal handlers for triggering webhooks when events occur.
"""

from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver

# Import models that trigger webhook events
# These imports are deferred to avoid circular imports


def trigger_webhook(tenant, event_type, data):
    """
    Trigger webhooks for a specific event.

    This function queues webhook deliveries for all active subscriptions
    that are subscribed to the given event type.

    Args:
        tenant: The Tenant instance
        event_type: String event type (e.g., 'appointment.created')
        data: Dict of event data to include in the payload
    """
    from .models import WebhookSubscription
    from .webhooks import queue_webhook_delivery

    # Find all active subscriptions for this tenant that want this event
    subscriptions = WebhookSubscription.objects.filter(
        tenant=tenant,
        is_active=True,
        events__contains=[event_type]
    )

    for subscription in subscriptions:
        queue_webhook_delivery(subscription, event_type, data)


# =============================================================================
# Appointment/Event Signals
# =============================================================================

# Note: These signal handlers are examples. They need to be connected to the
# actual models once we verify the model structure.

def handle_appointment_created(sender, instance, created, **kwargs):
    """Handle appointment creation."""
    if not created:
        return

    try:
        tenant = instance.tenant if hasattr(instance, 'tenant') else None
        if not tenant:
            return

        data = {
            'id': str(instance.id),
            'start_time': instance.start.isoformat() if instance.start else None,
            'end_time': instance.end.isoformat() if instance.end else None,
            'status': instance.status,
            # Add more fields as needed
        }

        trigger_webhook(tenant, 'appointment.created', data)
    except Exception:
        # Don't let webhook errors break the main flow
        pass


def handle_appointment_updated(sender, instance, **kwargs):
    """Handle appointment updates."""
    try:
        tenant = instance.tenant if hasattr(instance, 'tenant') else None
        if not tenant:
            return

        data = {
            'id': str(instance.id),
            'start_time': instance.start.isoformat() if instance.start else None,
            'end_time': instance.end.isoformat() if instance.end else None,
            'status': instance.status,
        }

        trigger_webhook(tenant, 'appointment.updated', data)
    except Exception:
        pass


def handle_appointment_cancelled(sender, instance, **kwargs):
    """Handle appointment cancellation."""
    try:
        # Check if status changed to CANCELLED
        if instance.status != 'CANCELLED':
            return

        tenant = instance.tenant if hasattr(instance, 'tenant') else None
        if not tenant:
            return

        data = {
            'id': str(instance.id),
            'start_time': instance.start.isoformat() if instance.start else None,
            'end_time': instance.end.isoformat() if instance.end else None,
            'status': instance.status,
        }

        trigger_webhook(tenant, 'appointment.cancelled', data)
    except Exception:
        pass


# =============================================================================
# Customer Signals
# =============================================================================

def handle_customer_created(sender, instance, created, **kwargs):
    """Handle customer creation."""
    if not created:
        return

    try:
        # Check if this is a customer
        if getattr(instance, 'role', None) != 'CUSTOMER':
            return

        tenant = instance.tenant if hasattr(instance, 'tenant') else None
        if not tenant:
            return

        data = {
            'id': str(instance.id),
            'email': instance.email,
            'name': instance.get_full_name() if hasattr(instance, 'get_full_name') else None,
        }

        trigger_webhook(tenant, 'customer.created', data)
    except Exception:
        pass


def handle_customer_updated(sender, instance, **kwargs):
    """Handle customer updates."""
    try:
        if getattr(instance, 'role', None) != 'CUSTOMER':
            return

        tenant = instance.tenant if hasattr(instance, 'tenant') else None
        if not tenant:
            return

        data = {
            'id': str(instance.id),
            'email': instance.email,
            'name': instance.get_full_name() if hasattr(instance, 'get_full_name') else None,
        }

        trigger_webhook(tenant, 'customer.updated', data)
    except Exception:
        pass


# =============================================================================
# Signal Registration
# =============================================================================

def register_webhook_signals():
    """
    Register signal handlers for webhook events.

    Call this from the app's ready() method to set up the signals.
    """
    try:
        from smoothschedule.scheduling.schedule.models import Event
        post_save.connect(handle_appointment_created, sender=Event, dispatch_uid='webhook_appointment_created')
        post_save.connect(handle_appointment_updated, sender=Event, dispatch_uid='webhook_appointment_updated')
    except ImportError:
        pass

    try:
        from smoothschedule.identity.users.models import User
        post_save.connect(handle_customer_created, sender=User, dispatch_uid='webhook_customer_created')
        post_save.connect(handle_customer_updated, sender=User, dispatch_uid='webhook_customer_updated')
    except ImportError:
        pass


# Auto-register signals when this module is imported
# (Called from apps.py ready() method)
