import zoneinfo
from django.shortcuts import redirect
from django.urls import reverse
from django.conf import settings
from django.utils import timezone
from core.models import CampaignSettings, Tenant

class LoginRequiredMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if not request.user.is_authenticated:
            path = request.path_info
            
            # Allow access to login, logout, admin, and any other exempted paths
            try:
                login_url = reverse('login')
                logout_url = reverse('logout')
            except:
                login_url = '/accounts/login/'
                logout_url = '/accounts/logout/'

            exempt_urls = [
                login_url,
                logout_url,
                '/admin/',
            ]
            
            # Check if path starts with any of the exempt URLs
            is_exempt = any(path.startswith(url) for url in exempt_urls)
            
            if not is_exempt:
                return redirect(f"{login_url}?next={path}")

        response = self.get_response(request)
        return response

class TimezoneMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        tzname = None
        
        # 1. Try to get tenant from session
        tenant_id = request.session.get("tenant_id")
        if tenant_id:
            try:
                campaign_settings = CampaignSettings.objects.get(tenant_id=tenant_id)
                tzname = campaign_settings.timezone
            except CampaignSettings.DoesNotExist:
                pass
        
        # 2. If not found and user is authenticated, maybe they are in admin?
        # In admin, we might not have tenant_id in session if they went directly there.
        # But this is a multi-tenant app, usually they select a campaign first.
        # If they are superuser in admin, we might want to default to something or let them see UTC.
        
        if tzname:
            try:
                timezone.activate(zoneinfo.ZoneInfo(tzname))
            except:
                timezone.deactivate()
        else:
            timezone.deactivate()

        return self.get_response(request)
