from django.db.models import Prefetch

from apps.core.models import SiteBranding, SiteContact
from apps.pages.models import CustomPage
from apps.products.models import MainProduct, SubProduct


def site_branding(request):
    return {"site_branding": SiteBranding.load()}


def site_contact(request):
    return {"site_contact": SiteContact.load()}


def navigation(request):
    main_products = (
        MainProduct.objects.filter(is_active=True)
        .prefetch_related(
            Prefetch(
                "sub_products",
                queryset=SubProduct.objects.filter(is_active=True).order_by(
                    "order", "name"
                ),
            )
        )
        .order_by("order", "name")
    )
    all_footer_products = list(main_products[:5])
    footer_main_products = all_footer_products[:4]
    footer_main_products_has_more = len(all_footer_products) == 5
    nav_custom_pages = CustomPage.objects.filter(
        is_published=True,
        show_in_nav=True,
    ).order_by("menu_order", "title")
    return {
        "nav_main_products": main_products,
        "nav_custom_pages": nav_custom_pages,
        "footer_main_products": footer_main_products,
        "footer_main_products_has_more": footer_main_products_has_more,
    }
