"""
ASGI config for N3wtSchool project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/
"""

import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.urls import  re_path
from django.conf import settings
from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'N3wtSchool.settings')

# Initialize Django ASGI application early to ensure the AppRegistry
# is populated before importing code that may import ORM models.
django_asgi_app = get_asgi_application()

# Import consumers after Django is initialized
from GestionMessagerie.consumers import ChatConsumer
from GestionMessagerie.middleware import JWTAuthMiddlewareStack

# WebSocket URL patterns
websocket_urlpatterns = [
    re_path(r'ws/chat/(?P<user_id>\w+)/$', ChatConsumer.as_asgi()),
]

# Créer l'application ASGI avec gestion des fichiers statiques
if settings.DEBUG:
    # En mode DEBUG, utiliser ASGIStaticFilesHandler pour servir les fichiers statiques
    http_application = ASGIStaticFilesHandler(django_asgi_app)
else:
    http_application = django_asgi_app

application = ProtocolTypeRouter({
    "http": http_application,
    "websocket": AllowedHostsOriginValidator(
        JWTAuthMiddlewareStack(
            URLRouter(websocket_urlpatterns)
        )
    ),
})
