from typing import Type

from django.db.models import QuerySet
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.permissions import AllowAny
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.serializers import Serializer

from apps.geology.models import Geology
from apps.geology.serializers import GeologySerializer, GeologyDetailSerializer


class GeologyView(GenericAPIView):
    permission_classes = [AllowAny]

    def get_serializer_class(self) -> Type[Serializer]:
        if self.request.method == "POST":
            return GeologySerializer
        return GeologyDetailSerializer

    def get_queryset(self) -> QuerySet[Geology]:
        return Geology.objects.all().select_related()

    def get(self, request: Request) -> Response:
        geology_id = request.query_params.get("id")
        category_id = request.query_params.get("category")
        if geology_id:
            geologies = Geology.objects.filter(id=geology_id)
        elif category_id:
            geologies = Geology.objects.filter(category_id=category_id)
        else:
            geologies = self.get_queryset()
        serializer = self.get_serializer(geologies, many=True)
        return Response(serializer.data)

    def post(self, request: Request) -> Response:
        serializer = self.get_serializer(
            data=request.data, context={"request": request}
        )
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
