"""Public storefront views (anonymous-accessible)."""

from django.http import Http404
from django.shortcuts import get_object_or_404, render

from ..models import HullListing, Shop
from ..permissions import can_manage


def detail(request, slug):
    shop = get_object_or_404(Shop, slug=slug)
    if not shop.is_published and not can_manage(request.user, shop):
        raise Http404("Shop not found")
    featured_listings = []
    grouped_listings = []
    if shop.section_enabled("hulls"):
        base = HullListing.objects.filter(shop=shop).select_related(
            "eve_type", "eve_type__eve_group"
        )
        featured_listings = list(
            base.filter(featured=True).order_by("featured_at", "eve_type__name")
        )
        grouped_listings = list(
            base.filter(featured=False).order_by(
                "eve_type__eve_group__name", "eve_type__name"
            )
        )
    view = request.GET.get("view", "grid")
    if view not in ("grid", "table"):
        view = "grid"
    return render(request, "storefront/detail.html", {
        "shop": shop,
        "is_preview": not shop.is_published,
        "featured_listings": featured_listings,
        "grouped_listings": grouped_listings,
        "view": view,
    })


def item_detail(request, slug, listing_id):
    shop = get_object_or_404(Shop, slug=slug)
    if not shop.is_published and not can_manage(request.user, shop):
        raise Http404("Shop not found")
    listing = get_object_or_404(
        HullListing.objects.select_related("eve_type", "eve_type__eve_group"),
        pk=listing_id, shop=shop,
    )
    return render(request, "storefront/item_detail.html", {
        "shop": shop,
        "listing": listing,
        "is_preview": not shop.is_published,
    })
