# coding: utf-8

from django.db.models import (
    Count,
    Exists,
    IntegerField,
    OuterRef,
    Prefetch,
    Q,
    Subquery,
)

from procu.api import models
from procu.rest import filters, generics, pagination
from .permissions import SearchPermission
from .serializers import ProductSerializer, ProductsQueryParams


class EnquiryProductList(generics.ListAPIView):
    pagination_class = pagination.PageNumberPagination
    permission_classes = (SearchPermission,)
    serializer_class = ProductSerializer
    query_params_serializer_class = ProductsQueryParams
    filter_backends = (filters.SearchFilter,)

    search_fields = ('name', 'comment')

    def get_queryset(self):
        qp_qs = (
            models.QuoteProduct.objects.prepared(
                tax=True, totals=False, **self.query_params
            )
            .select_related('quote', 'quote__supplier', 'currency')
            .filter(Q(price__isnull=False), Q(price__gt=0), Q(is_deleted=False))
            .order_by('is_replacement', 'price')
        )

        valid_products = (
            qp_qs.filter(enquiry_product=OuterRef('pk'))
            .order_by()
            .values('enquiry_product')
        )
        count_products = valid_products.annotate(c=Count('*')).values('c')

        return (
            models.EnquiryProduct.objects.select_related(
                'request', 'request__enquiry'
            )
            .prefetch_related(Prefetch('quote_products', qp_qs, 'offers'))
            .annotate(
                n_offers=Subquery(count_products, output_field=IntegerField()),
                exists=Exists(count_products),
            )
            .filter(request__isnull=False)
            .order_by('-exists', '-n_offers')
        )
