"""
Test-only middleware that replaces TenantMainMiddleware.

Instead of doing a domain lookup, it resolves the tenant
from the Domain table within the same DB transaction,
avoiding issues with savepoint-based test isolation.
"""
from django.db import connection

from apps.core.tenant.models import Tenant


class TestTenantMiddleware:
    """
    Lightweight tenant middleware for tests.

    Sets request.tenant and connection.tenant to the first
    Tenant found in the database (within the test transaction).
    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Find the tenant within the current test transaction
        tenant = Tenant.objects.first()
        if tenant:
            request.tenant = tenant
            connection.set_tenant(tenant)
        else:
            request.tenant = None

        response = self.get_response(request)
        return response
