from django.http import JsonResponse, HttpResponseForbidden
from django.shortcuts import render


def is_api_or_postman_request(request):
    """
    Detects if the incoming HTTP request is an API call or comes from an API client like Postman, cURL, or Insomnia.
    """
    accept = request.headers.get('accept', '').lower()
    content_type = request.headers.get('content-type', '').lower()
    requested_with = request.headers.get('x-requested-with', '').lower()
    user_agent = request.headers.get('user-agent', '').lower()
    path = request.path.lower()

    # Check for API headers, Postman/cURL/Insomnia user agent, or JSON requests
    is_json = 'application/json' in accept or 'application/json' in content_type
    is_ajax = requested_with == 'xmlhttprequest'
    is_postman_or_api_client = any(client in user_agent for client in ['postman', 'curl', 'insomnia', 'httpie'])
    is_api_path = path.startswith('/api/')

    return is_json or is_ajax or is_postman_or_api_client or is_api_path


class UnauthenticatedApiProtectionMiddleware:
    """
    Middleware that intercepts unauthenticated API and Postman requests to protected routes
    (/dashboard/*, /superadmin/*) and returns HTTP 401 (or HTTP 403) instead of 302 redirects.
    """

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

    def __call__(self, request):
        path = request.path.lower()

        # Protected path prefixes
        protected_prefixes = ('/dashboard/', '/superadmin/')

        if any(path.startswith(prefix) for prefix in protected_prefixes):
            if not request.user.is_authenticated:
                if is_api_or_postman_request(request):
                    return JsonResponse({
                        'error': 'Unauthorized',
                        'detail': 'Authentication required. Access denied for unauthenticated API request.'
                    }, status=401)
            elif path.startswith('/superadmin/') and not request.user.is_superuser:
                if is_api_or_postman_request(request):
                    return JsonResponse({
                        'error': 'Forbidden',
                        'detail': 'Superadmin privileges required.'
                    }, status=403)
                else:
                    return HttpResponseForbidden('Superadmin privileges required.')

        response = self.get_response(request)
        return response
