"""Fichiers lus par les moteurs de recherche : /robots.txt et /sitemap.xml."""

from django.contrib.sitemaps.views import sitemap
from django.http import HttpResponse
from django.urls import path
from django.views.decorators.cache import cache_page
from django.views.decorators.http import require_GET

from .sitemaps import SITEMAPS

# Le back-office et l'admin ne doivent pas apparaître dans Google. L'API reste ouverte :
# Google exécute le JavaScript des pages et peut avoir besoin de ses réponses.
DISALLOWED = ["/dashboard/", "/admin/"]

CACHE_SECONDS = 60 * 60


@require_GET
def robots_txt(request):
    lines = ["User-agent: *", *(f"Disallow: {p}" for p in DISALLOWED), ""]
    lines.append(f"Sitemap: {request.build_absolute_uri('/sitemap.xml')}")
    return HttpResponse("\n".join(lines) + "\n", content_type="text/plain; charset=utf-8")


urlpatterns = [
    path("robots.txt", cache_page(CACHE_SECONDS)(robots_txt), name="robots-txt"),
    path(
        "sitemap.xml",
        cache_page(CACHE_SECONDS)(sitemap),
        {"sitemaps": SITEMAPS},
        name="django.contrib.sitemaps.views.sitemap",
    ),
]
