from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from .models import Notification


def send_notification(user, title, message, order_id=None):
    """
    Send real-time notification to a specific user
    """
    try:
        Notification.objects.create(
            user=user,
            title=str(title or ""),
            message=str(message or ""),
            order_id=order_id,
        )
    except Exception:
        pass

    try:
        channel_layer = get_channel_layer()
    except Exception:
        # Keep API behavior working even when real-time backend is unavailable.
        return

    if channel_layer is None:
        return

    try:
        async_to_sync(channel_layer.group_send)(
            f"user_{user.id}",
            {
                "type": "send_notification",
                "message": {
                    "title": title,
                    "message": message,
                    "order_id": order_id,
                }
            }
        )
    except Exception:
        # Do not fail core business actions due to notification transport issues.
        return
