"""Not-found error detail tests."""

from __future__ import annotations

from collections.abc import AsyncGenerator

import pytest
from fastapi import FastAPI
from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.pool import StaticPool
from sqlmodel import Field, SQLModel
from sqlmodel.ext.asyncio.session import AsyncSession

from auen import CrudRouterBuilder


class Widget(SQLModel, table=True):
    widget_id: int | None = Field(default=None, primary_key=True)
    name: str


@pytest.mark.asyncio
async def test_not_found_includes_pk_name() -> None:
    """404 detail should include the primary key field name."""
    engine = create_async_engine(
        "sqlite+aiosqlite://",
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )
    async with engine.begin() as conn:
        await conn.run_sync(SQLModel.metadata.create_all)

    async def get_session() -> AsyncGenerator[AsyncSession, None]:
        async with AsyncSession(engine) as session:
            yield session

    app = FastAPI()
    app.include_router(
        CrudRouterBuilder.for_model(Widget, get_session)
        .with_id_field("widget_id")
        .build()
    )

    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as client:
        resp = await client.get("/widgets/999")

    assert resp.status_code == 404
    assert resp.json()["detail"] == "Widget with widget_id 999 not found"

    await engine.dispose()
