"""Transactional email when an administrator creates a user (no password in email)."""

from __future__ import annotations

import logging

from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode

from apps.core.notifications.emailing import absolute_portal_url, portal_base_url

logger = logging.getLogger(__name__)

User = get_user_model()


def send_admin_created_user_invitation(user: User) -> None:
    """
    Email a one-time set-password link (same token machinery as password reset).

    Inactive users may be unable to use the public “Forgot password” flow to obtain
    a new link; keep new accounts active=True when using invitations (see UserCreateForm).
    """
    uidb64 = urlsafe_base64_encode(force_bytes(user.pk))
    token = default_token_generator.make_token(user)
    reset_path = reverse(
        "accounts:password_reset_confirm",
        kwargs={"uidb64": uidb64, "token": token},
    )
    set_password_url = absolute_portal_url(reset_path)
    login_url = absolute_portal_url(reverse("accounts:login"))
    forgot_url = absolute_portal_url(reverse("accounts:password_reset"))

    recipient_name = user.get_full_name() or user.email.split("@")[0]
    body = (
        "An administrator has created an IILMP account for this email address.\n\n"
        "Use the button below to choose your password before you sign in. "
        "This link expires after a period of time for security (the same as a password reset).\n\n"
        f"If the link has expired, use Forgot password and enter {user.email}:\n{forgot_url}\n\n"
        f"After setting your password, sign in here:\n{login_url}"
    )
    plain = (
        "Your RUFORUM IILMP account\n\n"
        f"{body}\n\n"
        f"Set your password:\n{set_password_url}"
    )
    html = render_to_string(
        "notifications/emails/generic.html",
        {
            "notification": None,
            "recipient_name": recipient_name,
            "headline": "Your IILMP account is ready",
            "preheader": "Set your password to get started.",
            "body": body,
            "body_html": "",
            "action_url": set_password_url,
            "action_label": "Set your password",
            "portal_base": portal_base_url(),
            "preferences_path": reverse("core:notification_inbox"),
        },
    )
    send_mail(
        subject="Your RUFORUM IILMP account",
        message=plain,
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=[user.email],
        html_message=html,
        fail_silently=False,
    )
    logger.info("admin invitation email sent to %s", user.email)
