from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static


def superuser_only(request):
    return request.user.is_active and request.user.is_superuser

admin.site.has_permission = superuser_only

# Admin URL is configured via DJANGO_ADMIN_URL in .env (default: admin000)
_admin_url = settings.DJANGO_ADMIN_URL.strip('/') + '/'

urlpatterns = [
    path(_admin_url, admin.site.urls),
    path('', include('core.urls')),
    path('', include('companies.urls')),
    path('inventory/', include('inventory.urls')),
    path('sales/', include('sales.urls')),
    path('accounts/', include('accounts.urls')),
    path('api/', include('api.urls', namespace='api')),
    path('', include('subscriptions.public_urls')),
    path('webhooks/', include('subscriptions.webhook_urls')),
    path('subscription/', include('subscriptions.urls', namespace='subscriptions')),
    path('analytics/', include('analytics.urls', namespace='analytics')),
]


from django.urls import re_path
from django.views.static import serve

# Media files — explicitly structured to serve safely even in DEBUG=False
urlpatterns += [
    re_path(r'^media/(?P<path>.*)$', serve, {
        'document_root': settings.MEDIA_ROOT,
    }),
]

# ── Custom error handlers ─────────────────────────────────────────────────────
handler400 = 'core.views.error_400'
handler403 = 'core.views.error_403'
handler404 = 'core.views.error_404'
handler500 = 'core.views.error_500'
handler503 = 'core.views.error_503'