"""Sorting tests for list endpoints."""

from __future__ import annotations

from fastapi import FastAPI
from httpx import ASGITransport, AsyncClient
from tests.conftest import Book, SessionFactory

from auen import CrudRouterBuilder, FilterConfig, Operation


async def test_sort_descending(get_session: SessionFactory) -> None:
    app = FastAPI()
    app.include_router(
        CrudRouterBuilder.for_model(Book, get_session)
        .with_filters(FilterConfig(sort_fields=["title"]))
        .with_operations({Operation.CREATE, Operation.LIST})
        .build()
    )
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as c:
        await c.post("/books/", json={"title": "B", "isbn": "1"})
        await c.post("/books/", json={"title": "A", "isbn": "2"})
        resp = await c.get("/books/", params={"sort": "-title"})
        titles = [b["title"] for b in resp.json()]
        assert titles == ["B", "A"]


async def test_sort_disallowed_field(get_session: SessionFactory) -> None:
    app = FastAPI()
    app.include_router(
        CrudRouterBuilder.for_model(Book, get_session)
        .with_filters(FilterConfig(sort_fields=["title"]))
        .with_operations({Operation.LIST})
        .build()
    )
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as c:
        resp = await c.get("/books/", params={"sort": "isbn"})
        assert resp.status_code == 422
