from rest_framework import status
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from drf_spectacular.utils import extend_schema, OpenApiResponse, OpenApiExample

from api.account.serializers.objects_serializers import ZoneSerializer
from sitemanagement.models import Zone

from api.utils.decorators import handle_exceptions

@extend_schema(tags=['Зоны'])
class ZoneView(APIView):
    permission_classes = [IsAuthenticated]
    serializer_class = ZoneSerializer

    @extend_schema(
        summary="Получение зон для указанного объекта",
        description="Возвращает список зон для объекта по query-параметру objectId",
        responses={
            200: OpenApiResponse(
                response=ZoneSerializer,
                description="Зоны успешно получены",
                examples=[
                    OpenApiExample(
                        'Успешный ответ',
                        value=[
                            {
                                "id": 1,
                                "name": "Зона 1",
                                "floor": 1,
                                "image_path": "test_image_2.png",
                                "model_path": "/static-models/AerBIM-Monitor_ASM-HTViewer_Expo2017Astana_20250908_L_+76190.glb",
                                "order": 0,
                                "sensors": [
                                    {
                                        "id": 10,
                                        "name": "Датчик 1",
                                        "serial_number": "GA-123",
                                        "sensor_type": "Тип датчика 1"
                                    }
                                ]
                            }
                        ]
                    )
                ]
            )
        }
    )
    @handle_exceptions
    def get(self, request):
        """Получение всех зон для указанного объекта"""
        object_id = request.query_params.get('objectId') or request.query_params.get('object_id') or request.query_params.get('object')
        if not object_id:
            return Response({"error": "objectId query parameter is required"}, status=status.HTTP_400_BAD_REQUEST)

        try:
            zones = Zone.objects.filter(object_id=object_id).prefetch_related(
                'sensors',
                'sensors__sensor_type'
            ).order_by('order', 'name')

            serializer = ZoneSerializer(zones, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)
        except Zone.DoesNotExist:
            return Response({"error": "Зоны не найдены"}, status=status.HTTP_404_NOT_FOUND)