from django.utils import timezone

from apps.notifications.models import Channel, Notification, NotificationKind, NotificationStatus


def notify_user(user, title, body, kind=NotificationKind.GENERAL, project=None):
    if user is None:
        return None
    return Notification.objects.create(
        user=user,
        title=title,
        body=body,
        kind=kind,
        channel=Channel.IN_APP,
        status=NotificationStatus.SENT,
        sent_at=timezone.now(),
        project=project,
    )


def notify_project_investors(project, title, body, kind=NotificationKind.MILESTONE):
    from apps.investments.models import InvestmentStatus

    users = set()
    for investment in project.investments.filter(status=InvestmentStatus.ACTIVE).select_related("investor__user"):
        users.add(investment.investor.user)
    for user in users:
        notify_user(user, title, body, kind=kind, project=project)
