"""Auth tests: verify authentication enforcement."""

from __future__ import annotations

from httpx import AsyncClient
from tests.conftest import SessionFactory


async def test_no_credentials_returns_401(
    auth_client: AsyncClient,
) -> None:
    """Without X-User header, all mutating endpoints return 401."""
    resp = await auth_client.get("/books/")
    assert resp.status_code == 401

    resp = await auth_client.post(
        "/books/",
        json={"title": "X", "isbn": "Y"},
    )
    assert resp.status_code == 401


async def test_with_credentials_succeeds(authed_client: AsyncClient) -> None:
    """With X-User header, CRUD works."""
    resp = await authed_client.post(
        "/books/",
        json={
            "title": "The Pragmatic Programmer",
            "isbn": "978-0135957059",
        },
    )
    assert resp.status_code == 201

    book_id = resp.json()["id"]
    resp = await authed_client.get(f"/books/{book_id}")
    assert resp.status_code == 200


async def test_anonymous_read_allowed(get_session: SessionFactory) -> None:
    """allow_anonymous on LIST/READ lets unauthenticated users read."""
    from fastapi import FastAPI
    from httpx import ASGITransport, AsyncClient
    from tests.conftest import (
        Book,
        get_current_user,
    )

    from auen import AuthConfig, CrudRouterBuilder, Operation

    auth = AuthConfig(
        dependency=get_current_user,
        allow_anonymous={Operation.LIST, Operation.READ},
    )
    app = FastAPI()
    app.include_router(
        CrudRouterBuilder.for_model(Book, get_session).with_auth(auth).build()
    )
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as c:
        # Anonymous read should work
        resp = await c.get("/books/")
        assert resp.status_code == 200

        # Anonymous create should fail
        resp = await c.post(
            "/books/",
            json={"title": "X", "isbn": "Y"},
        )
        assert resp.status_code == 401
