"""
View decorators for subscription-based access control.
"""

from functools import wraps
from typing import Callable, List, Optional

import lark
from django.http import HttpResponseForbidden
from django.shortcuts import redirect

from .client import get_lark_client
from .utils import get_external_id_for_user


def subscription_required(
    rate_card_ids: Optional[List[str]] = None,
    redirect_url: Optional[str] = None,
):
    """
    Decorator that requires user to have an active subscription.

    Uses the user's external_id to look up their billing state in Lark.

    Args:
        rate_card_ids: Optional list of rate card IDs to check.
                       If None, any active subscription is sufficient.
        redirect_url: URL to redirect to if not subscribed.
                      If None, returns 403 Forbidden.

    Usage:
        @subscription_required()
        def premium_view(request):
            return render(request, 'premium.html')

        @subscription_required(rate_card_ids=['rc_pro', 'rc_enterprise'])
        def pro_view(request):
            return render(request, 'pro.html')

        @subscription_required(redirect_url='/pricing/')
        def feature_view(request):
            return render(request, 'feature.html')
    """

    def decorator(view_func: Callable):
        @wraps(view_func)
        def wrapper(request, *args, **kwargs):
            user = request.user

            if not user.is_authenticated:
                if redirect_url:
                    return redirect(redirect_url)
                return HttpResponseForbidden("Authentication required")

            # Check subscription using external_id
            try:
                external_id = get_external_id_for_user(user)
                client = get_lark_client()
                billing_state = client.customer_access.retrieve_billing_state(
                    external_id
                )

                if not billing_state.has_active_subscription:
                    if redirect_url:
                        return redirect(redirect_url)
                    return HttpResponseForbidden("Active subscription required")

                # Check specific rate cards if provided
                if rate_card_ids:
                    user_rate_cards = {
                        s.rate_card_id for s in (billing_state.active_subscriptions or [])
                    }
                    if not any(rc in user_rate_cards for rc in rate_card_ids):
                        if redirect_url:
                            return redirect(redirect_url)
                        return HttpResponseForbidden(
                            "Required subscription tier not found"
                        )

            except lark.APIError:
                if redirect_url:
                    return redirect(redirect_url)
                return HttpResponseForbidden("Unable to verify subscription")

            return view_func(request, *args, **kwargs)

        return wrapper

    return decorator
