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


def partner_list(request):
    partners = (
        ConsultingPartner.objects.filter(disable_listing=False)
        .order_by("name")
        .prefetch_related("services", "cloud_providers")
    )

    services = Service.objects.all().order_by("name")

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

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

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

    context = {
        "partners": partners,
        "services": services,
        "cloud_providers": CloudProvider.objects.all(),
    }
    return render(request, "services/partner_list.html", context)


def partner_detail(request, slug):
    partner = get_object_or_404(
        ConsultingPartner.objects.prefetch_related(
            "services",
            "services__categories",
            "services__offerings",
            "services__offerings__cloud_provider",
            "cloud_providers",
        ),
        slug=slug,
    )

    context = {
        "partner": partner,
        "services": partner.services.all(),
    }
    return render(request, "services/partner_detail.html", context)
