# dynamic_smtp_backend.py
from django.core.mail.backends.smtp import EmailBackend
from django.db import connection

class DynamicEmailBackend(EmailBackend):
    """Custom SMTP backend that fetches email settings from the database dynamically."""

    def _get_smtp_settings(self):
        DATABASE_TABLE = 'website_setting'
        try:
            with connection.cursor() as cursor:
                cursor.execute(f"SELECT * FROM {DATABASE_TABLE} LIMIT 1")
                row = cursor.fetchone()
                if row:
                    columns = [col[0] for col in cursor.description]
                    return dict(zip(columns, row))
        except Exception:
            return {}
        return {}

    def open(self):
        # Fetch latest SMTP settings before opening connection
        settings = self._get_smtp_settings()
        self.host = settings.get('smtp_host', self.host)
        self.port = int(settings.get('smtp_port', self.port))
        self.username = settings.get('smtp_user', self.username)
        self.password = settings.get('smtp_password', self.password)
        self.use_tls = bool(settings.get('smtp_tls', self.use_tls))
        self.use_ssl = bool(settings.get('smtp_ssl', self.use_ssl))
        # Set dynamic From email
        self.default_from_email = f"{settings.get('from_name', 'Admin')} <{settings.get('from_email', 'admin@example.com')}>"
        return super().open()
