from django.apps import AppConfig


class OrgsConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "orgs"
    verbose_name = "Organizations & Tenancy"

    def ready(self) -> None:  # pragma: no cover
        # Import signal handlers robustly to avoid attribute import issues
        import importlib
        try:
            importlib.import_module("orgs.signals")
        except Exception:
            # Avoid startup hard-fail if migrations/apps not ready; re-raise only in debug if needed
            raise

        # Monkey-patch User.__str__ to show "<username>, <fullname>"
        # This affects labels in forms and general stringification.
        try:
            from django.contrib.auth import get_user_model

            User = get_user_model()

            def _user_str(self):  # type: ignore[override]
                full = self.get_full_name().strip()
                return f"{self.username}, {full}" if full else f"{self.username}"

            # Assign only if not already customized
            if getattr(User.__str__, "__name__", None) != "_user_str":  # type: ignore[attr-defined]
                User.__str__ = _user_str  # type: ignore[assignment]
        except Exception:
            # Do not block app startup if something goes wrong
            pass
        return super().ready()
