from iurban_tenancy.fastapi import make_tenant_session


class _FakeTxn:
    async def __aenter__(self):
        return self

    async def __aexit__(self, *exc):
        return False


class _FakeSession:
    def __init__(self, calls: list):
        self.calls = calls

    async def __aenter__(self):
        return self

    async def __aexit__(self, *exc):
        return False

    def begin(self):
        return _FakeTxn()

    async def execute(self, stmt, params=None):
        self.calls.append((str(stmt), params or {}))


async def test_make_tenant_session_yields_a_session_with_tenant_applied():
    calls: list = []
    dependency = make_tenant_session(lambda: _FakeSession(calls), lambda: "tenant-1")  # type: ignore[arg-type]
    agen = dependency(tenant_id="tenant-1")
    session = await agen.__anext__()
    assert isinstance(session, _FakeSession)
    assert any("SET LOCAL app.current_tenant" in sql for sql, _ in calls)
    await agen.aclose()
