from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.conf import settings
from .models import EmailLog, Notification


def _send(recipient_email, subject, template_name, context):
    """Core email sender — logs every attempt."""
    context.setdefault('foundation_name', settings.FOUNDATION_NAME)
    context.setdefault('portal_url', settings.PORTAL_URL)
    try:
        html_message = render_to_string(template_name, context)
        send_mail(
            subject=subject,
            message='',
            html_message=html_message,
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[recipient_email],
            fail_silently=False,
        )
        EmailLog.objects.create(
            recipient_email=recipient_email,
            subject=subject,
            body=html_message,
            status=EmailLog.SENT,
        )
        return True
    except Exception as exc:
        EmailLog.objects.create(
            recipient_email=recipient_email,
            subject=subject,
            status=EmailLog.FAILED,
            error_message=str(exc),
        )
        return False


def notify_application_received(application):
    _send(
        recipient_email=application.email,
        subject=f'Application Received — {settings.FOUNDATION_NAME}',
        template_name='communications/email/application_received.html',
        context={'application': application},
    )


def notify_application_approved(user, application, temp_password):
    _send(
        recipient_email=application.email,
        subject=f'Congratulations! Your Application Has Been Approved — {settings.FOUNDATION_NAME}',
        template_name='communications/email/application_approved.html',
        context={
            'application': application,
            'user': user,
            'temp_password': temp_password,
        },
    )


def notify_application_rejected(application):
    _send(
        recipient_email=application.email,
        subject=f'Application Status Update — {settings.FOUNDATION_NAME}',
        template_name='communications/email/application_rejected.html',
        context={'application': application},
    )


def create_notification(recipient, title, message):
    """Create an in-app notification for a user."""
    Notification.objects.create(recipient=recipient, title=title, message=message)
