"""Notification helper — writes in-app notifications so actions taken by one
party become visible to the other party (and to staff via the admin portal),
and best-effort dispatches a push to any of that user's registered devices.
"""

from django.utils import timezone

from .models import DeviceToken, Notification


def push_notification(user, title, body, *, deal=None, channel=Notification.Channel.IN_APP):
    if user is None:
        return None
    notification = Notification.objects.create(
        user=user,
        deal=deal,
        title=title[:120],
        body=body,
        channel=channel,
    )
    _dispatch_push(user, title, body, deal=deal, notification=notification)
    return notification


def _dispatch_push(user, title, body, *, deal, notification):
    from .push import send_push  # deferred: keeps push.py's deps out of every import of this module

    tokens = DeviceToken.objects.filter(user=user, is_active=True)
    data = {"deal_id": str(deal.id), "deal_code": deal.code} if deal else {}
    sent_any = False
    for device in tokens:
        if send_push(device.token, title, body, data=data):
            sent_any = True
    if sent_any:
        notification.sent_at = timezone.now()
        notification.save(update_fields=["sent_at"])
