# django_core_micha/invitations/emails.py
from django.conf import settings
from django.core.mail import EmailMessage
from django.template.loader import render_to_string
import logging

logger = logging.getLogger(__name__)


def send_invite_or_reset_email(*, user, url, is_new_user: bool) -> None:
    """
    Generic helper: nimmt User + Link, holt sich Texte aus Templates
    und schickt die Mail raus.
    """

    ctx = {
        "user": user,
        "url": url,
        "is_new_user": is_new_user,
    }

    # 1) Subjekt
    if is_new_user:
        subject_template = "invitations/invite_subject.txt"
        body_template = "invitations/invite_body.txt"
    else:
        subject_template = "invitations/reset_subject.txt"
        body_template = "invitations/reset_body.txt"

    try:
        subject = render_to_string(subject_template, ctx).strip()
        body = render_to_string(body_template, ctx)
    except Exception:
        # Fallback, falls Templates fehlen (z. B. im frühen Setup)
        if is_new_user:
            subject = "Willkommen"
            body = f"Hallo,\n\nbitte setze dein Passwort hier:\n{url}\n"
        else:
            subject = "Passwort zurücksetzen"
            body = f"Hallo,\n\nbitte setze dein Passwort hier:\n{url}\n"

    if getattr(settings, "ENV_TYPE", "") == "local":
        logger.info("[LOCAL] Invite/Reset-Mail an %s: %s", user.email, url)
        return

    from_email = getattr(settings, "INVITATIONS_FROM_EMAIL", None)
    reply_to = getattr(settings, "INVITATIONS_REPLY_TO", None)

    headers = {}
    if reply_to:
        headers["Reply-To"] = reply_to

    email = EmailMessage(
        subject=subject,
        body=body,
        from_email=from_email,  # None → DEFAULT_FROM_EMAIL
        to=[user.email],
        headers=headers,
    )
    email.send(fail_silently=False)
