from .models import Notification


def create_notification(recipient, notif_type, title, body="", link="", sender=None):
    """Helper to create a notification and push via WebSocket."""
    if recipient == sender:
        return  # Don't notify yourself

    notif = Notification.objects.create(
        recipient=recipient,
        sender=sender,
        notif_type=notif_type,
        title=title,
        body=body,
        link=link,
    )

    # Push via WebSocket
    try:
        from channels.layers import get_channel_layer
        from asgiref.sync import async_to_sync
        import json

        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            f"notifications_{recipient.id}",
            {
                "type": "notification.send",
                "data": {
                    "id":           notif.id,
                    "notif_type":   notif.notif_type,
                    "title":        notif.title,
                    "body":         notif.body,
                    "link":         notif.link,
                    "is_read":      notif.is_read,
                    "created_at":   notif.created_at.isoformat(),
                    "sender_username": sender.username if sender else None,
                }
            }
        )
    except Exception:
        pass  # WebSocket push failed silently — REST still works

    return notif