# home/api/permissions.py

from functools import wraps
from django.http import JsonResponse
from django.conf import settings
from wagtail.models import Site

from hospit.tenant.models import TenantProfile



LOCALHOSTS = {"localhost", "127.0.0.1"}


def is_localhost(request):
    host = request.get_host().split(":")[0]
    return host in LOCALHOSTS or host.endswith(".localhost")


def tenant_api_protected(view_func):
    """
    Domain + API key protection for tenant-scoped API.
    """

    @wraps(view_func)
    def _wrapped(request, *args, **kwargs):
        site = Site.find_for_request(request)
        if not site:
            return JsonResponse({"detail": "Site not resolved"}, status=404)

        # =========================
        # DEV MODE: allow localhost
        # =========================
        if settings.DEBUG and is_localhost(request):
            return view_func(request, *args, **kwargs)

        # =========================
        # PROD MODE: strict check
        # =========================
        try:
            profile = TenantProfile.for_site(site)
        except TenantProfile.DoesNotExist:
            return JsonResponse({"detail": "Tenant profile not found"}, status=404)

        # 1️⃣ Domain check
        allowed_domain = None
        if profile.website:
            allowed_domain = profile.website.replace("https://", "").replace("http://", "").rstrip("/")

        request_host = request.get_host().split(":")[0]

        if allowed_domain and request_host != allowed_domain:
            return JsonResponse({"detail": "Invalid domain"}, status=403)

        # 2️⃣ API key check
        api_key = request.headers.get("X-API-KEY")
        if not api_key or api_key != profile.api_key:
            return JsonResponse({"detail": "Invalid API key"}, status=403)

        return view_func(request, *args, **kwargs)

    return _wrapped