from django.shortcuts import render, get_object_or_404
from .models import Insight, InsightCategory


def _active_categories():
    """Only categories that have at least one published post."""
    used_ids = Insight.objects.filter(status='published').values_list('category_id', flat=True).distinct()
    return InsightCategory.objects.filter(id__in=used_ids)


def insights_list(request):
    category_slug = request.GET.get('category')
    posts = Insight.objects.filter(status='published').order_by('-published_at')
    categories = _active_categories()
    active_category = None

    if category_slug:
        active_category = get_object_or_404(InsightCategory, slug=category_slug)
        posts = posts.filter(category=active_category)

    return render(request, 'public/insights.html', {
        'posts': posts,
        'categories': categories,
        'active_category': active_category,
    })


def insight_detail(request, slug):
    from apps.auction.models import AuctionListing
    post = get_object_or_404(Insight, slug=slug, status='published')
    related = Insight.objects.filter(status='published').exclude(pk=post.pk).order_by('-published_at')[:3]
    categories = _active_categories()
    domain_suggestions = AuctionListing.objects.filter(
        status=AuctionListing.STATUS_ACTIVE,
        asset_type=AuctionListing.TYPE_DOMAIN,
    ).order_by('-is_premium', '?')[:4]
    return render(request, 'public/insight_detail.html', {
        'post': post,
        'related': related,
        'categories': categories,
        'domain_suggestions': domain_suggestions,
    })
