from django.conf import settings
from django.http import Http404
from django.shortcuts import redirect
from django.urls import reverse
from .models import Organization

EXEMPT_PATHS = [
    '/login/',
    '/logout/',
    '/register/',
    '/trial-expired/',
    '/upgrade/',
    '/admin/',
    '/static/',
    '/media/',
    '/check-slug/',
]


class SubdomainMiddleware:
    """
    Resolves subdomain to Organization.
    Sets request.org, request.is_main_domain, request.subdomain.
    """

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

    def __call__(self, request):
        host        = request.get_host().split(':')[0].lower()
        main_domain = getattr(settings, 'MAIN_DOMAIN', 'avighnasolution.in')

        request.org            = None
        request.is_main_domain = False
        request.subdomain      = None

        if host in (main_domain, f'www.{main_domain}', 'localhost', '127.0.0.1'):
            request.is_main_domain = True

        elif host.endswith(f'.{main_domain}'):
            slug              = host.replace(f'.{main_domain}', '')
            request.subdomain = slug

            try:
                org = Organization.objects.get(slug=slug, is_active=True)
                request.org = org
            except Organization.DoesNotExist:
                raise Http404(f"Organization '{slug}' not found.")

        else:
            request.is_main_domain = True

        response = self.get_response(request)
        return response


class TrialExpiryMiddleware:
    """
    Checks if organization's trial has expired.
    Redirects to /trial-expired/ if expired.
    Exempt paths are not blocked.
    """

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

    def __call__(self, request):
        # Only check for authenticated users with an org
        if hasattr(request, 'user') and request.user.is_authenticated:
            user = request.user

            # Super admins are never blocked
            if not user.is_super_admin and user.org:
                org  = user.org
                path = request.path

                # Skip exempt paths
                is_exempt = any(path.startswith(p) for p in EXEMPT_PATHS)

                if not is_exempt:
                    # Auto-expire if trial is over
                    org.check_and_expire_trial()

                    # Block if trial expired
                    if org.trial_expired:
                        if path != '/trial-expired/':
                            return redirect('/trial-expired/')

        return self.get_response(request)
