import logging
from typing import Iterable

from django.core.mail import EmailMessage
from django.core.mail.backends.smtp import EmailBackend

from apps.notifications.models import EmailConfig

logger = logging.getLogger(__name__)


def get_active_email_config() -> EmailConfig | None:
    return EmailConfig.objects.filter(is_active=True, is_primary=True).order_by('-updated_at').first()


def send_email_using_active_config(
    *,
    subject: str,
    message: str,
    recipient_list: Iterable[str],
    purpose: str = 'notification',
) -> dict:
    recipients = [str(value).strip() for value in (recipient_list or []) if str(value).strip()]
    if not recipients:
        return {'ok': False, 'error': 'No recipient provided'}

    config = get_active_email_config()
    if not config:
        return {'ok': False, 'error': 'No active email configuration'}
    if not config.is_enabled:
        return {'ok': False, 'error': 'Active email configuration is disabled'}
    if purpose == 'otp' and not config.allow_otps:
        return {'ok': False, 'error': 'OTP email delivery is disabled'}
    if purpose == 'notification' and not config.allow_notifications:
        return {'ok': False, 'error': 'Notification email delivery is disabled'}

    backend = EmailBackend(
        host=config.host,
        port=config.port,
        username=config.username or None,
        password=config.password or None,
        use_tls=config.use_tls,
        use_ssl=config.use_ssl,
        fail_silently=False,
    )

    email = EmailMessage(
        subject=subject,
        body=message,
        from_email=config.from_email,
        to=recipients,
        connection=backend,
    )

    try:
        sent_count = email.send(fail_silently=False)
        if sent_count > 0:
            return {'ok': True, 'provider': config.provider, 'config_id': str(config.id)}
        return {'ok': False, 'error': 'Email backend did not send message'}
    except Exception as exc:
        logger.exception('Email send failed via active config: %s', exc)
        return {'ok': False, 'error': str(exc)}
