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


def provider_list(request):
    providers = (
        CloudProvider.objects.filter(disable_listing=False)
        .order_by("name")
        .prefetch_related("offerings", "consulting_partners")
    )

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

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


def provider_detail(request, slug):
    provider = get_object_or_404(
        CloudProvider.objects.prefetch_related(
            "offerings",
            "offerings__service",
            "offerings__plans",
            "consulting_partners",
        ),
        slug=slug,
    )

    # Get all services offered by this provider through offerings
    services = (
        Service.objects.filter(offerings__cloud_provider=provider)
        .distinct()
        .prefetch_related("categories")
    )

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