"""FastAPI integration: build a tenant-scoped session dependency.

Decoupled from auth on purpose — the app supplies `get_tenant_id` (a dependency that returns the
tenant id, typically wired from `iurban_auth.current_user`). This SDK only owns the data layer.
"""

from collections.abc import AsyncIterator, Callable
from typing import Any

from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker

from . import apply_tenant


def make_tenant_session(
    sessionmaker: async_sessionmaker[AsyncSession],
    get_tenant_id: Callable[..., Any],
) -> Callable[..., AsyncIterator[AsyncSession]]:
    """Return a FastAPI dependency that yields a session with the tenant set for the request.

        # app wiring (auth from iurban-auth):
        def tenant_id(user = Depends(current_user)) -> str:
            if not user.tenant_id: raise HTTPException(403)
            return user.tenant_id
        TenantSession = Annotated[AsyncSession, Depends(make_tenant_session(async_session, tenant_id))]
    """

    async def _tenant_session(
        tenant_id: Any = Depends(get_tenant_id),
    ) -> AsyncIterator[AsyncSession]:
        async with sessionmaker() as session:
            async with session.begin():
                await apply_tenant(session, tenant_id)
                yield session

    return _tenant_session
