from channels.db import database_sync_to_async
from django.core.cache import cache


class TenantFetcher:
    """
    Async helper to fetch tenant objects with caching for WebSocket requests.
    """

    def __init__(self, tenant_model, cache_timeout=300):
        self.tenant_model = tenant_model
        self.cache_timeout = cache_timeout

    @database_sync_to_async
    def get_tenant(self, tenant_name):
        """
        Get tenant by schema name, using cache to reduce DB hits.
        """
        cache_key = f"ws_tenant_{tenant_name}"
        tenant = cache.get(cache_key)
        if tenant:
            return tenant

        try:
            tenant = self.tenant_model.objects.get(schema_name=tenant_name)
            cache.set(cache_key, tenant, self.cache_timeout)
            return tenant
        except self.tenant_model.DoesNotExist:
            return None
