from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
from lchttp.json import json_dumps
from typing import Any, Mapping


class FastJsonResponse(HttpResponse):
    """
    Implementation of Django's JsonResponse, using the ``json_dumps``
    library for performance.
    """

    def __init__(
        self,
        data: Mapping[str, Any],
        encoder: type[DjangoJSONEncoder] = DjangoJSONEncoder,  # noqa
        safe: bool = True,
        json_dumps_params: Mapping[str, Any] | None = None,  # noqa
        **kwargs: Any,
    ):
        if safe and not isinstance(data, dict):
            raise TypeError(
                'In order to allow non-dict objects to be serialized set the '
                'safe parameter to False.'
            )
        kwargs.setdefault('content_type', 'application/json')

        data = json_dumps(data)

        super().__init__(content=data, **kwargs)


__all__ = [
    'FastJsonResponse',
]
