from django.contrib.auth.mixins import UserPassesTestMixin
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from django.shortcuts import redirect
from .models import Subscription  # Make sure to import your Subscription model

class SubscriptionRequiredMixin(UserPassesTestMixin):
    """Mixin that checks if the user has an active subscription."""
    
    def test_func(self):
        # Get the current user
        user = self.request.user
        
        # Check if the user is authenticated
        if user.is_authenticated:
            # Get the subscription for the user
            try:
                subscription = Subscription.objects.get(user=user)
                # Check if the subscription is active
                if subscription.end_date > timezone.now():
                    return True
            except Subscription.DoesNotExist:
                return False  # No subscription found
        return False  # User not authenticated or subscription is expired

    def handle_no_permission(self):
        # Redirect to a specific page if the user does not have permission
        return redirect('apply_for_application')  # Change to your subscription page URL


def subscription_required(view_func):
    @login_required
    def _wrapped_view(request, *args, **kwargs):
        # Get the current user
        user = request.user
        
        # Check if the user has an active subscription
        try:
            subscription = Subscription.objects.get(user=user)
            if subscription.end_date > timezone.now():
                return view_func(request, *args, **kwargs)
        except Subscription.DoesNotExist:
            pass
        
        # If no active subscription, redirect to subscription required page
        return redirect('apply_for_application')  # Change to your subscription page URL

    return _wrapped_view