"""Views for the file_validator app."""
from django.http import HttpRequest, HttpResponse, JsonResponse
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic.edit import FormView

from sage_validation.file_validator.forms import CSVUploadForm


def index_view(request: HttpRequest) -> HttpResponse:
    """Render the index page."""
    return render(request, "index.html")


class CSVUploadView(FormView):
    """View for uploading a CSV file."""

    template_name = "upload.html"
    form_class = CSVUploadForm
    success_url = reverse_lazy("upload-file")

    def get_context_data(self, **kwargs: dict) -> dict:
        """Render the form with no error message on GET request."""
        context = super().get_context_data(**kwargs)
        context["error"] = None
        context["message"] = None
        return context

    def form_valid(self, form: CSVUploadForm) -> JsonResponse:  # noqa: ARG002
        """Handle the CSV validation and passes appropriate success messages to the template."""
        return JsonResponse({"status": "success", "message": "File is valid"})

    def form_invalid(self, form: CSVUploadForm) -> JsonResponse:
        """Handle the form when it is invalid (e.g., wrong file type or validation errors)."""
        return JsonResponse({"status": "error", "errors": [form.errors]}, status=400)