"""
inventory/services/notification_service.py
──────────────────────────────────────────
Email helpers for the maker-checker workflow on inventory transactions.
"""

import logging

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.mail import send_mail
from django.template.loader import render_to_string

logger = logging.getLogger(__name__)

User = get_user_model()


def _get_approvers():
    """Return all active superusers + members of 'Inventory Approvers' group."""
    superusers = User.objects.filter(is_superuser=True, is_active=True)
    group_members = User.objects.filter(
        groups__name="Inventory Approvers", is_active=True
    )
    return (superusers | group_members).distinct()


def _review_url(pending_tx) -> str:
    site = getattr(settings, "SITE_URL", "").rstrip("/")
    return f"{site}/admin/inventory/pendinginventorytransaction/{pending_tx.pk}/review/"


def notify_approvers(pending_tx) -> None:
    """Send an approval-request email to all eligible approvers."""
    approvers = _get_approvers()
    emails = [u.email for u in approvers if u.email]
    if not emails:
        logger.warning("notify_approvers: no approver emails configured.")
        return

    subject = (
        f"[Inventory] Approval needed: {pending_tx.get_op_type_display()} "
        f"— {pending_tx.book.title}"
    )
    context = {
        "pending": pending_tx,
        "review_url": _review_url(pending_tx),
    }
    html_body = render_to_string("inventory/email/tx_approval_request.html", context)
    text_body = (
        f"Approval needed for inventory transaction.\n\n"
        f"Operation : {pending_tx.get_op_type_display()}\n"
        f"Book      : {pending_tx.book.title}\n"
        f"Submitted : {pending_tx.submitted_by}\n"
        f"Reference : {pending_tx.reference or '—'}\n"
        f"Notes     : {pending_tx.notes or '—'}\n\n"
        f"Review at : {_review_url(pending_tx)}\n"
    )

    try:
        send_mail(
            subject=subject,
            message=text_body,
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=emails,
            html_message=html_body,
        )
    except Exception:  # never block the stock request on email — but record it
        logger.exception("Failed to email approvers about pending tx #%d", pending_tx.pk)
        return
    logger.info("Approval request sent to %d approver(s) for pending tx #%d.", len(emails), pending_tx.pk)


def notify_maker_decision(pending_tx) -> None:
    """Email the original submitter when their request is approved or rejected."""
    maker = pending_tx.submitted_by
    if not maker or not maker.email:
        return

    approved = pending_tx.status == "approved"
    subject = (
        f"[Inventory] Your {pending_tx.get_op_type_display()} was "
        f"{'approved' if approved else 'rejected'}"
    )
    context = {
        "pending": pending_tx,
        "approved": approved,
    }
    html_body = render_to_string("inventory/email/tx_decision.html", context)
    text_body = (
        f"Your inventory transaction has been {'approved' if approved else 'rejected'}.\n\n"
        f"Operation : {pending_tx.get_op_type_display()}\n"
        f"Book      : {pending_tx.book.title}\n"
        f"Status    : {'Approved ✓' if approved else 'Rejected ✗'}\n"
        + (f"Reason    : {pending_tx.rejection_reason}\n" if not approved else "")
        + f"Reviewed by: {pending_tx.reviewed_by}\n"
    )

    try:
        send_mail(
            subject=subject,
            message=text_body,
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[maker.email],
            html_message=html_body,
        )
    except Exception:  # never block the approval on email — but record it
        logger.exception("Failed to email %s the decision on pending tx #%d", maker.email, pending_tx.pk)
