"""Django app configuration for aa_skip_email."""

from django.apps import AppConfig
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import gettext_lazy as _


class AaSkipEmailConfig(AppConfig):
    """
    Register signal handlers for User email transitions.

    Django auto-discovers this AppConfig because it is the only
    ``AppConfig`` subclass in the package — ``INSTALLED_APPS`` can keep
    using the bare ``"aa_skip_email"`` entry.
    """

    name = "aa_skip_email"
    default_auto_field = "django.db.models.BigAutoField"
    verbose_name = _("Allianceauth Skip Email")

    def ready(self) -> None:
        """Validate settings and import signal handlers."""
        self._validate_domain_setting()
        # Importing the module is sufficient — the @receiver decorators
        # register the handlers as a side effect of import. No heavy
        # I/O / network here, per Django guidance for AppConfig.ready().
        from aa_skip_email import (
            signals_handlers,  # noqa: F401  # pyright: ignore[reportUnusedImport]
        )

    @staticmethod
    def _validate_domain_setting() -> None:
        """
        Fail fast on a malformed ``AA_SKIP_EMAIL_DOMAIN``.

        Catches the most common misconfigurations at process start
        instead of letting them surface on the first SSO registration:
        missing value, embedded ``@`` (someone wrote a full email),
        whitespace, or a single-label "domain" that won't even pass
        Django's EmailField validation.
        """
        from aa_skip_email.app_settings import AA_SKIP_EMAIL_DOMAIN

        domain = AA_SKIP_EMAIL_DOMAIN
        if not domain:
            raise ImproperlyConfigured(
                "AA_SKIP_EMAIL_DOMAIN must not be empty."
            )
        if "@" in domain:
            raise ImproperlyConfigured(
                f"AA_SKIP_EMAIL_DOMAIN must not contain '@' (got {domain!r}); supply only the domain part."  # noqa: E501
            )
        if any(ch.isspace() for ch in domain):
            raise ImproperlyConfigured(
                f"AA_SKIP_EMAIL_DOMAIN must not contain whitespace (got {domain!r})."  # noqa: E501
            )
        if "." not in domain:
            raise ImproperlyConfigured(
                f"AA_SKIP_EMAIL_DOMAIN must contain at least one '.' so the resulting email validates as a real address (got {domain!r}; try 'no-email.invalid')."  # noqa: E501
            )
