"""تست Middleware تشخیص tenant."""
from __future__ import annotations

from fastapi import FastAPI, Request
from httpx import ASGITransport, AsyncClient

from app.middlewares.tenant import TenantResolutionMiddleware
from app.models.tenant import Tenant


def _build_probe_app() -> FastAPI:
    """اپ کوچک برای بازتاب tenant تشخیص‌داده‌شده از request.state."""
    probe = FastAPI()
    probe.add_middleware(TenantResolutionMiddleware)

    @probe.get("/whoami")
    async def whoami(request: Request):
        tid = getattr(request.state, "tenant_id", None)
        slug = getattr(request.state, "tenant_slug", None)
        return {"tenant_id": str(tid) if tid else None, "tenant_slug": slug}

    return probe


async def test_resolve_by_tenant_slug_header(session):
    tenant = Tenant(name="Mid Co", slug="midco")
    session.add(tenant)
    await session.commit()

    transport = ASGITransport(app=_build_probe_app())
    async with AsyncClient(transport=transport, base_url="http://testserver") as ac:
        resp = await ac.get("/whoami", headers={"X-Tenant-Slug": "midco"})
    assert resp.status_code == 200
    assert resp.json()["tenant_slug"] == "midco"


async def test_resolve_by_tenant_id_header(session):
    tenant = Tenant(name="Mid Co2", slug="midco2")
    session.add(tenant)
    await session.commit()
    tid = str(tenant.id)

    transport = ASGITransport(app=_build_probe_app())
    async with AsyncClient(transport=transport, base_url="http://testserver") as ac:
        resp = await ac.get("/whoami", headers={"X-Tenant-ID": tid})
    assert resp.status_code == 200
    assert resp.json()["tenant_id"] == tid


async def test_unresolved_tenant_is_none(session):
    transport = ASGITransport(app=_build_probe_app())
    async with AsyncClient(transport=transport, base_url="http://testserver") as ac:
        resp = await ac.get("/whoami", headers={"X-Tenant-Slug": "unknown-xyz"})
    assert resp.status_code == 200
    assert resp.json()["tenant_id"] is None
