from functools import wraps

from django.http import JsonResponse, HttpResponse
from django.shortcuts import redirect

from extensions.consts import UserRoles


def require_ajax(view_func):
    @wraps(view_func)
    def _wrapped_view(request, *args, **kwargs):
        if not request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            return JsonResponse({'error': 'Only AJAX requests are allowed.'}, status=400)
        return view_func(request, *args, **kwargs)

    return _wrapped_view


def allowed_roles(allowed_roles: list[UserRoles]):
    """
    @param allowed_roles must not be empty
    """

    def decorator(views_func):
        def wrapper_func(request, *args, **kwargs):
            roles = [role.slug for role in request.user.profile.roles.all()]
            allowed_role_names = [role.value for role in allowed_roles]
            if any(item in roles for item in allowed_role_names):
                return views_func(request, *args, **kwargs)
            else:
                return HttpResponse('you are not allow', status=401)

        return wrapper_func

    return decorator


def profile_complete_needed(view_func):
    @wraps(view_func)
    def _wrapped_view(request, *args, **kwargs):
        if not request.user.profile or not request.user.profile.is_completed:
            return redirect("accounts:profile")
        return view_func(request, *args, **kwargs)

    return _wrapped_view


def superuser_required(views_func):
    def wrapper_func(request, *args, **kwargs):
        user = request.user
        if user.is_superuser:
            return views_func(request, *args, **kwargs)
        else:
            return redirect('dashboard:vodDashboard')

    return wrapper_func


def staffuser_required(views_func):
    def wrapper_func(request, *args, **kwargs):
        user = request.user
        if user.is_staff:
            return views_func(request, *args, **kwargs)
        else:
            return redirect('dashboard:vodDashboard')

    return wrapper_func
