from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend

from apps.companies.models import Company
from apps.calls.constants import BotType
from apps.appointments.models import Appointment
from apps.appointments.serializers import AppointmentSerializer
from apps.appointments.filters import AppointmentFilter
from apps.appointments.pagination import AppointmentLimitOffsetPagination


class ServiceAppointmentViewSet(viewsets.ModelViewSet):
    """ViewSet for managing Service appointments only (SERVICE_BOT appointments)."""
    queryset = Appointment.objects.all()
    serializer_class = AppointmentSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = AppointmentLimitOffsetPagination
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_class = AppointmentFilter
    search_fields = ['name', 'twilio_call_sid', 'call__from_number', 'appointment_phone']
    ordering_fields = ['scheduled_date', 'created_at', 'name']
    ordering = ['-scheduled_date']

    def get_queryset(self):
        user = self.request.user

        if user.is_superuser:
            return self.queryset.filter(bot_type=BotType.SERVICE_BOT.value).order_by('-scheduled_date')

        if user.active_company:
            try:
                return self.queryset.filter(
                    company=user.active_company, 
                    bot_type=BotType.SERVICE_BOT.value
                ).order_by('-scheduled_date')
            except Company.DoesNotExist:
                return self.queryset.none()

        return self.queryset.none()
