# pxy_dashboard/middleware.py
import re
from django.conf import settings
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.deprecation import MiddlewareMixin

EXEMPT_URLS = [
    reverse("account_login"),
    reverse("account_logout"),
    reverse("account_signup"),
    reverse("account_reset_password"),
    reverse("account_reset_password_done"),
    # These can't be reversed without args
    "/accounts/password/reset/key/done/",
]
EXEMPT_URLS += [re.compile(r"^accounts/password/reset/key/.+$")]
EXEMPT_URLS += [re.compile(expr) for expr in [
    r"^admin/",
    r"^accounts/",
    r"^static/",
    r"^media/",
]]

# ————— aquí añadimos los webhooks de WhatsApp —————
# Como path_info.lstrip("/") será "whatsapp/webhook/" y "whatsapp/webhook/verify/"
EXEMPT_URLS += [
    "pxy_whatsapp/webhook/",
    "pxy_whatsapp/webhook/verify/",
]
EXEMPT_URLS += [
    re.compile(r"^pxy_whatsapp/webhook/?$"),
    re.compile(r"^pxy_whatsapp/webhook/verify/?$"),
]

# Webhook de Telegram
EXEMPT_URLS += [
    "bots/webhook/",          # prefijo general
    re.compile(r"^bots/webhook/.+/$"),  # con <bot_name> al final
]

# Webhook de Facebook Pages (pxy_meta_pages)
EXEMPT_URLS += [
    re.compile(r"^pxy_meta_pages/webhook/?$"),
]

class LoginRequiredMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if not request.user.is_authenticated:
            path = request.path_info.lstrip("/")
            if not any(url.match(path) if hasattr(url, 'match') else path == url.lstrip("/") for url in EXEMPT_URLS):
                return redirect(settings.LOGIN_URL)
