from django.shortcuts import render, get_object_or_404
from django.db.models import Q
from hub.services.models import (
    Service,
    ConsultingPartner,
    CloudProvider,
    Category,
)


def service_list(request):
    services = (
        Service.objects.filter(disable_listing=False)
        .order_by("-is_featured", "is_coming_soon", "name")
        .prefetch_related(
            "categories",
            "offerings",
            "offerings__cloud_provider",
            "offerings__plans",
            "consulting_partners",
            "external_links",
        )
    )
    cloud_providers = CloudProvider.objects.all()
    categories = Category.objects.filter(parent=None).prefetch_related("children")

    # Handle category filter
    if request.GET.get("category"):
        category_id = request.GET.get("category")
        category = get_object_or_404(Category, id=category_id)
        subcategories = Category.objects.filter(parent=category)
        services = services.filter(
            Q(categories=category) | Q(categories__in=subcategories)
        ).distinct()

    # Handle cloud provider filter
    if request.GET.get("cloud_provider"):
        provider_id = request.GET.get("cloud_provider")
        services = services.filter(offerings__cloud_provider_id=provider_id).distinct()

    # Handle consulting partner filter
    if request.GET.get("consulting_partner"):
        partner_id = request.GET.get("consulting_partner")
        services = services.filter(consulting_partners__id=partner_id).distinct()

    # Handle search
    if request.GET.get("search"):
        query = request.GET.get("search")
        services = services.filter(
            Q(name__icontains=query)
            | Q(description__icontains=query)
            | Q(offerings__description__icontains=query)
        ).distinct()

    context = {
        "services": services,
        "cloud_providers": cloud_providers,
        "categories": categories,
        "consulting_partners": ConsultingPartner.objects.all(),
    }
    return render(request, "services/service_list.html", context)


def service_detail(request, slug):
    service = get_object_or_404(
        Service.objects.prefetch_related(
            "categories",
            "offerings",
            "offerings__cloud_provider",
            "offerings__plans",
            "consulting_partners",
            "external_links",
        ),
        slug=slug,
    )

    context = {
        "service": service,
    }
    return render(request, "services/service_detail.html", context)
