from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from crm.models.office import Office
from crm.serializers.office import OfficeSerializer

class OfficeViewSet(viewsets.ModelViewSet):
    queryset = Office.objects.all()
    serializer_class = OfficeSerializer
    
    def get_queryset(self):
        queryset = super().get_queryset()
        # Filter by active offices by default
        if self.request.query_params.get('active_only', 'true').lower() == 'true':
            queryset = queryset.filter(is_active=True)
        return queryset
    
    @action(detail=False, methods=['get'])
    def default(self, request):
        """Get the default office"""
        try:
            default_office = Office.get_default_office()
            if default_office:
                serializer = self.get_serializer(default_office)
                return Response(serializer.data)
            else:
                return Response(
                    {'detail': 'No default office found'}, 
                    status=status.HTTP_404_NOT_FOUND
                )
        except Exception as e:
            return Response(
                {'detail': f'Error retrieving default office: {str(e)}'}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    
    @action(detail=False, methods=['get'])
    def by_location(self, request):
        """Get office by location code"""
        location_code = request.query_params.get('location_code')
        if not location_code:
            return Response(
                {'detail': 'location_code parameter is required'}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        
        try:
            office = Office.get_office_by_location(location_code)
            if office:
                serializer = self.get_serializer(office)
                return Response(serializer.data)
            else:
                return Response(
                    {'detail': f'No office found for location: {location_code}'}, 
                    status=status.HTTP_404_NOT_FOUND
                )
        except Exception as e:
            return Response(
                {'detail': f'Error retrieving office: {str(e)}'}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
