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 company_portfolio_business.models.company_portfolio_business import CompanyPortfolioBusiness
from company_portfolio_business_category.models.company_portfolio_business_category import CompanyPortfolioBusinessCategory
from company_portfolio_business.serializers.company_image_serializer import CompanyImageListSerializer


class CompanyCategoryImageListAPIView(APIView):
    @swagger_auto_schema(
        manual_parameters=[
            openapi.Parameter(
                'company_id',
                openapi.IN_QUERY,
                description="ID of the company",
                type=openapi.TYPE_INTEGER,
                required=True
            ),
            openapi.Parameter(
                'category_id',
                openapi.IN_QUERY,
                description="ID of the business category",
                type=openapi.TYPE_INTEGER,
                required=True
            ),
        ],
        responses={200: CompanyImageListSerializer()}
    )
    
    def get(self, request):
        company_id = request.query_params.get('company_id')
        category_id = request.query_params.get('category_id')

        if not company_id or not category_id:
            return Response(
                {"detail": "Both company_id and category_id are required."},
                status=status.HTTP_400_BAD_REQUEST
            )

        entries = CompanyPortfolioBusiness.objects.filter(
            company_id=company_id,
            category_id=category_id
        )

        if not entries.exists():
            return Response(
                {"detail": "No images found for this company and category."},
                status=status.HTTP_404_NOT_FOUND
            )

        category = entries.first().category_id

        data = {
            "category_id": category.id,
            "category_name": category.name,
            "company_id": int(company_id),
            "images": [entry.image_url for entry in entries]
        }

        serializer = CompanyImageListSerializer(data)
        return Response(serializer.data, status=status.HTTP_200_OK)