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

from apps.tenants.models import Tenant

from .models import Brand


def _enabled(request):
    """Brands is a module, so a site without it should 404 rather than render.

    A tenant that has not bought the module still has the code, and without
    this check its /events/ would work anyway, which makes the module
    meaningless and confuses what a plan actually grants.
    """
    tenant = getattr(request, 'tenant', None) or Tenant.objects.filter(is_master=True).first()
    if tenant is None:
        return False
    return tenant.has_module('brands')


def brand_index(request):
    if not _enabled(request):
        raise Http404
    brands = Brand.objects.filter(is_active=True)
    return render(request, 'public/brands.html', {'brands': brands})


def brand_detail(request, slug):
    """Served from the top level, so this is the last route tried.

    Anything that reaches here matched no other pattern in config/urls.py. If
    it is not a brand either, it is a genuine 404 and should say so rather
    than falling through to the domain-for-sale page.
    """
    if not _enabled(request):
        raise Http404
    brand = get_object_or_404(Brand, slug=slug, is_active=True)
    siblings = Brand.objects.filter(is_active=True).exclude(pk=brand.pk)
    return render(request, 'public/brand_detail.html', {
        'brand': brand,
        'siblings': siblings,
    })
