# programmer/utils/email_notifications.py
from django.core.mail import send_mail, EmailMultiAlternatives
from django.template.loader import render_to_string
from django.conf import settings
from django.utils.html import strip_tags
import logging

logger = logging.getLogger(__name__)


def send_callback_notification(callback_request):
    """
    Отправляет уведомление о новой заявке на обратный звонок
    """
    try:
        subject = f'🚨 Новая заявка на обратный звонок от {callback_request.name}'

        # HTML версия письма
        html_message = render_to_string('emails/callback_notification.html', {
            'callback': callback_request,
            'site_url': settings.ALLOWED_HOSTS[0] if settings.ALLOWED_HOSTS else 'localhost',
        })

        # Текстовая версия письма
        plain_message = strip_tags(html_message)

        # Проверяем настройки email
        if not all([settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD]):
            logger.error("Email settings are not configured properly")
            return False

        # Отправляем email
        send_mail(
            subject=subject,
            message=plain_message,
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=settings.ADMIN_EMAILS,
            html_message=html_message,
            fail_silently=False,
        )

        logger.info(f"Email notification sent successfully for callback #{callback_request.id}")
        return True

    except Exception as e:
        logger.error(f"Error sending email notification: {e}")
        return False


def send_test_email():
    """
    Функция для тестирования отправки email
    """
    try:
        send_mail(
            subject='📧 Test Email from Django',
            message='This is a test email from your Django application.',
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=settings.ADMIN_EMAILS,
            fail_silently=False,
        )
        return True
    except Exception as e:
        logger.error(f"Test email failed: {e}")
        return False
