"""
Base forms and views for HTMX integration.
"""

from django.http import JsonResponse
from django.views.generic.edit import FormView


class HTMXFormView(FormView):
    """Base FormView that supports field-level validation endpoints for HTMX.

    Subclasses can call `validate_field` to return JSON errors for a single field.
    """

    def validate_field(self, field_name):
        """Return JSON with errors for a single field based on the current form."""
        form = self.get_form()
        form.is_valid()  # populate errors
        errors = form.errors.get(field_name, [])
        return JsonResponse({"field": field_name, "errors": errors})

    def post(self, request, *args, **kwargs):
        # If HTMX field validation pattern: ?field=name
        if request.headers.get("HX-Request") == "true" and request.GET.get("validate_field"):
            return self.validate_field(request.GET.get("validate_field"))
        return super().post(request, *args, **kwargs)
