import pytest

_VALID_CREDS = {"username": "testowner", "password": "testpassword"}


@pytest.mark.asyncio
async def test_login_success(authed_client):
    client, _ = authed_client
    response = await client.post("/api/v1/auth/token", json=_VALID_CREDS)
    assert response.status_code == 200
    body = response.json()
    assert isinstance(body.get("access_token"), str)
    assert len(body["access_token"]) > 0
    assert body.get("token_type") == "bearer"
    assert body.get("expires_in", 0) > 0


@pytest.mark.asyncio
async def test_login_wrong_password(authed_client):
    client, _ = authed_client
    response = await client.post(
        "/api/v1/auth/token",
        json={"username": "testowner", "password": "wrongpassword"},
    )
    assert response.status_code == 401
    assert response.json().get("code") == "invalid_credentials"


@pytest.mark.asyncio
async def test_login_wrong_username(authed_client):
    client, _ = authed_client
    response = await client.post(
        "/api/v1/auth/token",
        json={"username": "notowner", "password": "testpassword"},
    )
    assert response.status_code == 401
    assert response.json().get("code") == "invalid_credentials"


@pytest.mark.asyncio
async def test_login_missing_password(authed_client):
    client, _ = authed_client
    response = await client.post("/api/v1/auth/token", json={"username": "testowner"})
    assert response.status_code == 422


@pytest.mark.asyncio
async def test_login_missing_username(authed_client):
    client, _ = authed_client
    response = await client.post("/api/v1/auth/token", json={"password": "testpassword"})
    assert response.status_code == 422
