import requests
from django.shortcuts import redirect
from django.contrib import messages
from functools import wraps

def check_subscription(view_func):
    @wraps(view_func)
    def wrapper(request, *args, **kwargs):
        context_function_name = getattr(request, "function_name", "Unknown")

        url = "https://products.hexagoninfosoft.in/admin/vms/subscription/vmssubscription"
        payload = {"company_id": "hexagonvms"}

        try:
            api_response = requests.post(url, json=payload, timeout=5)
            try:
                response_data = api_response.json()
            except ValueError:
                messages.error(
                    request,
                    f"Invalid response from subscription API (HTTP {api_response.status_code}).",
                    extra_tags="danger",
                )
                return _redirect_to_login(request)

            if response_data.get("status") and "data" in response_data:
                sub_data = response_data["data"]
                sub_status = sub_data.get("sub_status", 0)
                expired_flag = response_data.get("expired", False)
                message_text = response_data.get("message", "")

                # ❌ Expired/inactive subscription
                if sub_status == 0 or expired_flag:
                    messages.error(
                        request,
                        message_text or "Your subscription has expired!",
                        extra_tags="danger",
                    )
                    return _redirect_to_login(request)

                # ⚠️ Expiring soon
                elif sub_status == 1 and not expired_flag:
                    if message_text and message_text != "Your subscription is active!":
                        messages.warning(request, message_text, extra_tags="warning")

                # ✅ Active subscription — allow access
            else:
                messages.error(request, "Unable to verify subscription.", extra_tags="danger")
                return _redirect_to_login(request)

        except requests.exceptions.RequestException as e:
            messages.error(request, f"API connection error: {str(e)}", extra_tags="danger")
            return _redirect_to_login(request)

        # ✅ Continue normal view if active
        return view_func(request, *args, **kwargs)

    return wrapper


# Helper function for proper redirect
def _redirect_to_login(request):
    """Redirect user to correct login page depending on their role/path"""
    if request.path.startswith("/admin"):
        return redirect("admin_login")
    elif request.path.startswith("/employee"):
        return redirect("employee_login")
    else:
        return redirect("gate_keeper")