"""Tests for ``mgf.fastapi.setup_lifespan``."""

from __future__ import annotations

from fastapi import FastAPI
from fastapi.testclient import TestClient
from mgf.common import AppContext

from mgf.fastapi import setup_lifespan


class TestSetupLifespan:
    def test_bootstrap_runs_at_app_startup(self) -> None:
        app = FastAPI(
            lifespan=setup_lifespan(app_name="test-app", app_version="0.0.1"),
        )

        @app.get("/identity")
        def _identity() -> dict[str, str]:
            ctx = app.state.mgf_context
            return {"app": ctx.app_name, "version": ctx.app_version}

        with TestClient(app) as client:
            response = client.get("/identity")
        assert response.status_code == 200
        assert response.json() == {"app": "test-app", "version": "0.0.1"}

    def test_app_state_carries_mgf_context(self) -> None:
        app = FastAPI(
            lifespan=setup_lifespan(app_name="test-app", app_version="0.0.1"),
        )
        with TestClient(app):
            ctx = app.state.mgf_context
            assert isinstance(ctx, AppContext)
            assert ctx.app_name == "test-app"

    def test_lifespan_shutdown_runs_on_exit(self) -> None:
        app = FastAPI(
            lifespan=setup_lifespan(app_name="test-app", app_version="0.0.1"),
        )
        with TestClient(app) as _client:
            # Within the context the bootstrapped wiring is active.
            assert hasattr(app.state, "mgf_context")
        # After exit, the bootstrap rollback ran. The state attribute
        # still exists (we don't clean app.state); but the context is
        # shut down — we just smoke-test that the lifespan exited
        # cleanly without raising.
