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


def offering_list(request):
    offerings = (
        ServiceOffering.objects.filter(disable_listing=False)
        .order_by("service")
        .select_related("service", "cloud_provider")
        .prefetch_related(
            "service__categories",
            "plans",
        )
    )

    cloud_providers = CloudProvider.objects.all()
    categories = Category.objects.filter(parent=None).prefetch_related("children")
    services = Service.objects.all().order_by("name")

    # Handle cloud provider filter
    if request.GET.get("cloud_provider"):
        provider_id = request.GET.get("cloud_provider")
        offerings = offerings.filter(cloud_provider_id=provider_id)

    # 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)
        offerings = offerings.filter(
            Q(service__categories=category) | Q(service__categories__in=subcategories)
        ).distinct()

    # Handle service filter
    if request.GET.get("service"):
        service_id = request.GET.get("service")
        offerings = offerings.filter(service_id=service_id)

    # Handle search
    if request.GET.get("search"):
        query = request.GET.get("search")
        offerings = offerings.filter(
            Q(service__name__icontains=query)
            | Q(description__icontains=query)
            | Q(cloud_provider__name__icontains=query)
        ).distinct()

    context = {
        "offerings": offerings,
        "cloud_providers": cloud_providers,
        "categories": categories,
        "services": services,
    }
    return render(request, "services/offering_list.html", context)


def offering_detail(request, provider_slug, service_slug):
    offering = get_object_or_404(
        ServiceOffering.objects.select_related(
            "service", "cloud_provider"
        ).prefetch_related("plans"),
        cloud_provider__slug=provider_slug,
        service__slug=service_slug,
    )

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