"""Django view adapter.

Returns a CSRF-exempt async view function that can be mounted in ``urlpatterns``::

    path("pillar/", pillar.django_view()),
"""
from __future__ import annotations

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from pillar._client import Pillar


def make_django_view(pillar: Pillar) -> Any:
    """Return an async Django view function wired to *pillar*."""
    from django.http import JsonResponse
    from django.views.decorators.csrf import csrf_exempt

    @csrf_exempt
    async def view(request: Any) -> JsonResponse:
        body = request.body
        headers = {
            "X-Pillar-Signature": request.META.get("HTTP_X_PILLAR_SIGNATURE", ""),
        }
        result, status_code = await pillar.handle(body, headers)
        return JsonResponse(result, status=status_code)

    return view
