"""Real outbound email via Gmail SMTP — signup verification and order/account
notifications to customers, pickers, and admin. Sending failures are logged
and swallowed, never raised, so a flaky SMTP connection can't break signup,
checkout, or order status updates."""

import logging

from django.conf import settings
from django.core.mail import EmailMessage, send_mail

logger = logging.getLogger(__name__)


def send_email(to_email, subject, body):
    if not to_email:
        return
    try:
        send_mail(
            subject=subject,
            message=body,
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[to_email],
            fail_silently=False,
        )
    except Exception:
        logger.exception('Failed to send email to %s (subject=%r)', to_email, subject)


def notify_admin(subject, body):
    send_email(settings.ADMIN_NOTIFICATION_EMAIL, f'[PickkerMarket] {subject}', body)


def send_contact_message(name, from_email, message, to_email):
    body = (
        f'New message from the PickkerMarket contact form.\n\n'
        f'Name: {name}\n'
        f'Email: {from_email}\n\n'
        f'{message}'
    )
    try:
        email = EmailMessage(
            subject=f'[PickkerMarket Contact] {name}',
            body=body,
            from_email=settings.DEFAULT_FROM_EMAIL,
            to=[to_email],
            reply_to=[from_email] if from_email else None,
        )
        email.send(fail_silently=False)
        return True
    except Exception:
        logger.exception('Failed to send contact form message from %s', from_email)
        return False
