"""Create in-app (and optional email) notifications for users."""
from django.conf import settings
from django.core.mail import send_mail
from django.utils import timezone

from .models import UserNotification

SIGNATURE = '-- PEZAJOB'


def _absolute_url(path):
    return f'{settings.SITE_URL.rstrip("/")}{path}'


def create_user_notification(
    *,
    recipient,
    title,
    body,
    notification_type,
    path='',
    sender=None,
    button_text='View',
    send_email=False,
):
    """Persist an in-app notification; optionally email the recipient."""
    redirect_url = _absolute_url(path) if path else ''

    UserNotification.objects.create(
        recipient=recipient,
        sender=sender,
        title=title,
        subject=title,
        body=body,
        message=body,
        notification_type=notification_type,
        redirect_url=redirect_url,
        button_text=button_text,
        is_read=False,
        created_at=timezone.now(),
    )

    if send_email and recipient.email:
        send_mail(
            subject=title,
            message=f'{body}\n\n{redirect_url}\n\n{SIGNATURE}' if redirect_url else f'{body}\n\n{SIGNATURE}',
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[recipient.email],
            fail_silently=True,
        )


def unread_notification_count(user):
    if not user or not getattr(user, 'is_authenticated', False):
        return 0
    return UserNotification.objects.filter(recipient=user, is_read=False).count()
