from uuid import uuid4

from fastapi.testclient import TestClient

from backend.app.main import app

client = TestClient(app)


def test_login_returns_token_and_user() -> None:
    response = client.post(
        "/api/auth/login",
        json={"username": "demo", "password": "railgame123"},
    )
    assert response.status_code == 200

    payload = response.json()
    assert "accessToken" in payload
    assert payload["tokenType"] == "bearer"
    assert payload["user"]["username"] == "demo"


def test_login_with_invalid_credentials_fails() -> None:
    response = client.post(
        "/api/auth/login",
        json={"username": "demo", "password": "wrong"},
    )
    assert response.status_code == 401


def test_me_endpoint_returns_current_user() -> None:
    login = client.post(
        "/api/auth/login",
        json={"username": "demo", "password": "railgame123"},
    )
    token = login.json()["accessToken"]

    response = client.get("/api/auth/me", headers={"Authorization": f"Bearer {token}"})
    assert response.status_code == 200
    assert response.json()["username"] == "demo"


def test_register_creates_user_and_returns_token() -> None:
    username = f"player_{uuid4().hex[:8]}"
    response = client.post(
        "/api/auth/register",
        json={
            "username": username,
            "password": "testpass123",
            "fullName": "Test Player",
        },
    )
    assert response.status_code == 201
    payload = response.json()
    assert payload["user"]["username"] == username
    assert payload["tokenType"] == "bearer"

    me = client.get(
        "/api/auth/me",
        headers={"Authorization": f"Bearer {payload['accessToken']}"},
    )
    assert me.status_code == 200
    assert me.json()["username"] == username


def test_register_duplicate_username_returns_conflict() -> None:
    username = f"dupe_{uuid4().hex[:8]}"
    first = client.post(
        "/api/auth/register",
        json={"username": username, "password": "firstpass"},
    )
    assert first.status_code == 201

    duplicate = client.post(
        "/api/auth/register",
        json={"username": username, "password": "secondpass"},
    )
    assert duplicate.status_code == 409
    assert duplicate.json()["detail"] == "Username already exists"
