from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi

from service.models.services import Services
from company_services.models.company import Companies
from company_services.serializers.company_simple_serializer import CompanySimpleSerializer


class CompaniesByCategorySerializer(APIView):
    @swagger_auto_schema(
        manual_parameters=[
            openapi.Parameter(
                'category_services_id',
                openapi.IN_QUERY,
                description="ID of the service category",
                type=openapi.TYPE_INTEGER,
                required=True
            ),
        ],
        responses={200: CompanySimpleSerializer(many=True)}
    )
    def get(self, request):
        category_id = request.query_params.get('category_services_id')

        if not category_id:
            return Response(
                {"detail": "category_id is required."},
                status=status.HTTP_400_BAD_REQUEST
            )

        # Get all companies offering services in this category
        services = Services.objects.filter(category_services_id=category_id).select_related('company')
        companies = Companies.objects.filter(id__in=services.values_list('company_id', flat=True).distinct())

        serializer = CompanySimpleSerializer(companies, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)