"""
Middleware for handling errors in HTMX requests.
"""

import logging

from django.http import HttpResponseServerError
from django.template.loader import render_to_string

logger = logging.getLogger(__name__)


class HTMXErrorMiddleware:
    """Catch exceptions on HTMX requests and return formatted error partials."""

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

    def __call__(self, request):
        try:
            return self.get_response(request)
        except Exception:
            logger.exception("Error during request")
            if request.headers.get("HX-Request") == "true":
                html = render_to_string(
                    "htmx/components/error_message.html",
                    {
                        "title": "Server error",
                        "message": "An unexpected error occurred.",
                    },
                )
                return HttpResponseServerError(html)
            raise
