from django.core.management.base import BaseCommand

from apps.core.notifications.models import Notification, NotificationPreference
from apps.core.notifications.tasks import dispatch_notification_channel


class Command(BaseCommand):
    help = "Retry email delivery for notifications that failed previously."

    def handle(self, *args, **options):
        qs = (
            Notification.objects.filter(email_sent=False)
            .exclude(email_error="")
            .select_related("recipient")[:100]
        )
        count = 0
        for n in qs:
            n.email_error = ""
            n.save(update_fields=["email_error"])
            dispatch_notification_channel.delay(
                n.pk,
                NotificationPreference.Channel.EMAIL,
                {"subject": "RUFORUM IILMP notification", "body": n.message},
            )
            count += 1
        self.stdout.write(self.style.SUCCESS(f"Queued {count} notification(s) for retry."))
