from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from .models import Classroom
from .serializers import ClassroomSerializer, ClassroomListSerializer
from permissions import DynamicModelPermission
from organization.mixins import TenantViewSetMixin

class ClassroomViewSet(TenantViewSetMixin, viewsets.ModelViewSet):
    queryset = Classroom.objects.all()
    permission_classes = [IsAuthenticated, DynamicModelPermission]

    def get_serializer_class(self):
        if self.action == 'list':
            return ClassroomListSerializer
        return ClassroomSerializer

    @action(detail=False, methods=['post'])
    def get_classrooms_for_routine(self, request):
        timeslot_id = request.data.get('timeslot', None)
        day_of_week = request.data.get('day_of_week', None)
        organization = getattr(request, 'organization', None)

        from django.db.models import Q
        classrooms = Classroom.objects.all()
        if organization:
            classrooms = classrooms.filter(Q(organization=organization) | Q(is_global=True))
        serializer = ClassroomListSerializer(
            classrooms,
            many=True,
            context={'timeslot': timeslot_id, 'day_of_week': day_of_week}
        )
        return Response(serializer.data)
