from celery import shared_task
from django.utils import timezone

from apps.notifications.models import Notification, NotificationEvent
from apps.notifications.services import DomainEventService


@shared_task
def retry_pending_notification_events_task():
    pending = NotificationEvent.objects.filter(processing_status=NotificationEvent.ProcessingStatus.PENDING)[:100]
    count = 0
    for ev in pending:
        count += DomainEventService.process_event(ev)
    return {"retried_notifications": count}


@shared_task
def purge_expired_notifications_task():
    now = timezone.now()
    qs = Notification.objects.filter(expires_at__isnull=False, expires_at__lt=now, is_mandatory_critical=False)
    deleted, _ = qs.delete()
    return {"purged": deleted}

