"""Email sender for notifications, via Django's configured EMAIL_BACKEND
(Microsoft Graph / Office365 in production, console backend in dev).

Everything is best-effort: any failure (misconfigured backend, network) is
swallowed so an email failure never breaks the DB-notification flow that
calls it, matching fcm.py's contract.
"""

import logging

from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string

logger = logging.getLogger(__name__)


def _absolute_link(link):
    if not link:
        return ""
    if link.startswith("http://") or link.startswith("https://"):
        return link
    return f"{settings.FRONTEND_URL.rstrip('/')}/{link.lstrip('/')}"


def _send(to_email, title, message, link):
    html = render_to_string("notifications/email_notification.html", {
        "title": title,
        "message": message,
        "link": _absolute_link(link),
    })
    mail = EmailMultiAlternatives(subject=title, body=message, to=[to_email])
    mail.attach_alternative(html, "text/html")
    mail.send()


def _log(user, to_email, title, notification_type, status, error=""):
    from .models import EmailLog

    try:
        EmailLog.objects.create(
            user=user,
            recipient_email=to_email,
            subject=title,
            notification_type=notification_type,
            status=status,
            error=error[:500],
        )
    except Exception:
        logger.exception("email log write failed for %s", to_email)


def send_to_user(user, *, title, body, link="", notification_type=""):
    """Email a single user. Returns True if sent, False otherwise. Always
    writes an EmailLog row (sent or failed) regardless of outcome."""
    if not user.email:
        return False
    try:
        _send(user.email, title, body, link)
        _log(user, user.email, title, notification_type, "sent")
        return True
    except Exception as exc:
        logger.exception("email send failed for user %s", getattr(user, "id", "?"))
        _log(user, user.email, title, notification_type, "failed", str(exc))
        return False


def send_to_users(payloads):
    """Send one email per payload. Payload dict keys: user, title, body, link,
    notification_type.

    Best-effort per-message: one failure doesn't stop the rest. Returns the
    number of emails sent successfully. Logs every attempt.
    """
    sent = 0
    for p in payloads:
        user = p["user"]
        if not user.email:
            continue
        title = p["title"]
        notification_type = p.get("notification_type", "")
        try:
            _send(user.email, title, p["body"], p.get("link", ""))
            _log(user, user.email, title, notification_type, "sent")
            sent += 1
        except Exception as exc:
            logger.exception("email send failed for user %s", getattr(user, "id", "?"))
            _log(user, user.email, title, notification_type, "failed", str(exc))
    return sent
