"""
Mail credentials come from the database. Nothing here reads .env.

.env is a file on disk that ends up in backups, in synced folders and in
whatever copies of the tree exist. The Settings row is in PostgreSQL, and the
passwords in it are encrypted at rest. So the panel is the only place these
are configured, and an empty Settings row means mail does not send rather than
quietly falling back to a stale address nobody remembers setting.
"""
from django.core.mail.backends.smtp import EmailBackend


def _site_settings():
    """The master tenant's settings row, or None if it cannot be read."""
    try:
        from apps.pages.models import SiteSettings
        from apps.tenants.models import Tenant
        return SiteSettings.load(Tenant.objects.filter(is_master=True).first())
    except Exception:
        return None


class SiteSettingsEmailBackend(EmailBackend):
    """SMTP host and credentials, read from Settings at send time."""

    def __init__(self, **kwargs):
        site = _site_settings()
        if site is not None and (site.smtp_host or '').strip():
            kwargs.setdefault('host',     site.smtp_host.strip())
            kwargs.setdefault('port',     site.smtp_port or 465)
            kwargs.setdefault('username', (site.smtp_user or '').strip())
            kwargs.setdefault('password', site.smtp_password or '')
            kwargs.setdefault('use_ssl',  site.smtp_use_ssl)
            kwargs.setdefault('use_tls',  site.smtp_use_tls)
        super().__init__(**kwargs)


def outgoing_address():
    """The address everything is sent as. Settings only."""
    site = _site_settings()
    if site is None:
        return ''
    return (site.smtp_user or '').strip()


def support_credentials():
    """The support mailbox as (address, password). Settings only."""
    site = _site_settings()
    if site is None:
        return '', ''
    return (site.support_email or '').strip(), (site.support_password or '')


def support_imap():
    """The support mailbox host and port. Host defaults to the SMTP host."""
    site = _site_settings()
    if site is None:
        return '', 993
    host = (site.support_imap_host or site.smtp_host or '').strip()
    return host, int(site.support_imap_port or 993)
