# home/api/tenant.py

from django.http import JsonResponse
from django.views.decorators.http import require_GET
from django.core.cache import cache
from django.conf import settings
from wagtail.models import Site

from hospit.tenant.models import TenantProfile
from .utils import build_absolute_media_url
from .permissions import tenant_api_protected
from .rate_limit import tenant_rate_limited


CACHE_KEY_PREFIX = "tenant_profile_v1"
CACHE_TTL = getattr(settings, "TENANT_CACHE_TTL", 60 * 5)


@require_GET
@tenant_rate_limited
@tenant_api_protected
def tenant_profile_api(request):
    """
    Public tenant profile API (site-scoped).
    """

    site = Site.find_for_request(request)
    if not site:
        return JsonResponse({"detail": "Site not resolved"}, status=404)

    cache_key = f"{CACHE_KEY_PREFIX}:site:{site.id}:{site.hostname}"

    cached = cache.get(cache_key)
    if cached:
        return JsonResponse(cached)

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

    data = {
        "tenant": {
            "id": site.id,
            "name": site.site_name,
            "domain": site.hostname,
        },
        "branding": {
            "logo": {
                "url": build_absolute_media_url(
                    request,
                    profile.logo.file.url if profile.logo else None
                ),
                "alt": site.site_name,
            }
        },
        "business": {
            "description": profile.description,
            "website": profile.website,
        },
        "location": {
            "address": profile.address,
            "latitude": float(profile.latitude) if profile.latitude else None,
            "longitude": float(profile.longitude) if profile.longitude else None,
        },
        "socials": profile.socials or [],
    }

    cache.set(cache_key, data, timeout=CACHE_TTL)
    return JsonResponse(data)