from django.contrib.auth import get_user_model

from .models import Notification, NotificationSetting


def notify(notification_type, *, title, message='', link_path=''):
    """Fan out a notification to every active user whose role has this type enabled."""
    enabled_roles = NotificationSetting.objects.filter(
        notification_type=notification_type, enabled=True,
    ).values_list('role', flat=True)
    if not enabled_roles:
        return

    User = get_user_model()
    recipients = User.objects.filter(role__name__in=list(enabled_roles), is_active=True)

    Notification.objects.bulk_create([
        Notification(
            recipient=user,
            notification_type=notification_type,
            title=title,
            message=message,
            link_path=link_path,
        )
        for user in recipients
    ])
