# core/email_utils.py
"""
Email notification utilities for SwiftPOS.
All emails are sent via SSL SMTP as configured in settings.
Sender name: "SwiftPOS Software"
"""
import threading
from django.core.mail import send_mail, EmailMultiAlternatives
from django.conf import settings
from django.utils import timezone
from django.template.loader import render_to_string


def _get_admin_emails():
    """Return list of admin email addresses from settings."""
    raw = getattr(settings, 'ADMIN_EMAIL', '')
    emails = [e.strip() for e in raw.split(',') if e.strip()]
    return emails or []


def _send_in_background(fn, *args, **kwargs):
    """Run email sending in a daemon thread so it never blocks the request."""
    t = threading.Thread(target=fn, args=args, kwargs=kwargs, daemon=True)
    t.start()


# ─────────────────────────────────────────────
#  LOW STOCK ALERT
# ─────────────────────────────────────────────

def _do_send_low_stock(product):
    admins = _get_admin_emails()
    if not admins or not settings.EMAIL_HOST_USER:
        return
    subject = f"Inventory Alert — Low Stock: {product.name}"
    body = (
        f"Hi,\n\n"
        f"This is an automated alert from SwiftPOS.\n\n"
        f"Product: {product.name} (SKU: {product.sku})\n"
        f"Current Stock: {product.stock_quantity} {product.unit_of_measure}\n"
        f"Minimum Level: {product.minimum_stock} {product.unit_of_measure}\n\n"
        f"Please restock this item as soon as possible to avoid stockouts.\n\n"
        f"—\nSwiftPOS Software\nThis is an automated notification."
    )
    try:
        send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, admins, fail_silently=True)
    except Exception:
        pass


def send_low_stock_alert(product):
    """Send low-stock alert in background thread."""
    _send_in_background(_do_send_low_stock, product)


# ─────────────────────────────────────────────
#  NEW CREDIT CUSTOMER ALERT
# ─────────────────────────────────────────────

def _do_send_credit_alert(customer_name, customer_phone, order_number, balance):
    admins = _get_admin_emails()
    if not admins or not settings.EMAIL_HOST_USER:
        return
    subject = f"Credit Transaction — New Balance Recorded"
    body = (
        f"Hi,\n\n"
        f"A new credit transaction has been recorded in SwiftPOS.\n\n"
        f"Customer: {customer_name}\n"
        f"Phone: {customer_phone or 'N/A'}\n"
        f"Order Reference: {order_number}\n"
        f"Outstanding Balance: {balance}\n\n"
        f"Please follow up to collect payment.\n\n"
        f"—\nSwiftPOS Software\nThis is an automated notification."
    )
    try:
        send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, admins, fail_silently=True)
    except Exception:
        pass


def send_credit_customer_alert(customer_name, customer_phone, order_number, balance):
    """Send credit customer alert in background thread."""
    _send_in_background(_do_send_credit_alert, customer_name, customer_phone, order_number, balance)


# ─────────────────────────────────────────────
#  DAILY REPORT
# ─────────────────────────────────────────────

def _do_send_daily_report(date):
    from sales.models import POSOrder, POSOrderItem
    from django.db.models import Sum, Count
    from decimal import Decimal

    admins = _get_admin_emails()
    if not admins or not settings.EMAIL_HOST_USER:
        return

    orders = POSOrder.objects.filter(created_at__date=date, status='completed')
    total_revenue = orders.aggregate(t=Sum('final_amount'))['t'] or Decimal('0')
    total_count = orders.count()
    credit_outstanding = orders.filter(balance_amount__gt=0).aggregate(t=Sum('balance_amount'))['t'] or Decimal('0')

    total_profit = Decimal('0')
    items = POSOrderItem.objects.filter(order__in=orders).select_related('product')
    for item in items:
        cost = item.product.cost_price or Decimal('0')
        total_profit += (item.unit_price - cost) * item.quantity

    subject = f"Daily Operations Summary — {date.strftime('%d %B %Y')}"
    body = (
        f"Hi,\n\n"
        f"Here is the automated end-of-day report for {date.strftime('%A, %d %B %Y')}.\n\n"
        f"{'─' * 40}\n"
        f"  Total Orders       : {total_count}\n"
        f"  Total Revenue      : {total_revenue:,.2f}\n"
        f"  Estimated Profit   : {total_profit:,.2f}\n"
        f"  Outstanding Credit : {credit_outstanding:,.2f}\n"
        f"{'─' * 40}\n\n"
        f"Payment Breakdown:\n"
    )

    for method in ['cash', 'transfer', 'pos', 'mobile_money', 'credit']:
        m_rev = orders.filter(payment_method=method).aggregate(t=Sum('final_amount'))['t'] or Decimal('0')
        m_count = orders.filter(payment_method=method).count()
        if m_count > 0:
            body += f"  {method.replace('_', ' ').title():15}: {m_rev:>12,.2f} ({m_count} orders)\n"

    body += (
        f"\n—\nSwiftPOS Software\n"
        f"This report was generated automatically at end of day."
    )

    try:
        send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, admins, fail_silently=True)
    except Exception:
        pass


def send_daily_report(date=None):
    """Send daily report. date defaults to yesterday."""
    if date is None:
        date = (timezone.now() - timezone.timedelta(days=1)).date()
    _send_in_background(_do_send_daily_report, date)
