# backend/tests/test_tournaments.py
import pytest
from httpx import AsyncClient

pytestmark = pytest.mark.anyio


async def test_create_tournament(
    client: AsyncClient, auth_headers, valid_tournament_payload
):
    response = await client.post(
        "/tournaments", json=valid_tournament_payload, headers=auth_headers
    )
    assert response.status_code == 200
    data = response.json()
    assert data["name"] == "Test Tournament"
    assert len(data["teams"]) == 4
    assert len(data["courts"]) == 2
    assert "id" in data


async def test_list_tournaments(
    client: AsyncClient, auth_headers, valid_tournament_payload
):
    await client.post(
        "/tournaments", json=valid_tournament_payload, headers=auth_headers
    )

    response = await client.get("/tournaments")
    assert response.status_code == 200
    data = response.json()
    assert len(data) >= 1
    assert data[0]["name"] == "Test Tournament"


async def test_delete_tournament(
    client: AsyncClient, auth_headers, valid_tournament_payload
):
    create_res = await client.post(
        "/tournaments", json=valid_tournament_payload, headers=auth_headers
    )
    t_id = create_res.json()["id"]

    del_res = await client.delete(f"/tournaments/{t_id}", headers=auth_headers)
    assert del_res.status_code == 200

    get_res = await client.get(f"/tournaments/{t_id}")
    assert get_res.status_code == 404


async def test_get_tournament_detail(
    client: AsyncClient, auth_headers, valid_tournament_payload
):
    create_res = await client.post(
        "/tournaments", json=valid_tournament_payload, headers=auth_headers
    )
    t_id = create_res.json()["id"]

    # 1. Test Detail Endpoint
    response = await client.get(f"/tournaments/{t_id}")
    assert response.status_code == 200
    data = response.json()

    # Should HAVE metadata
    assert len(data["teams"]) == 4

    # Should HAVE matches (since we merged nodes into matches and put them in Detail)
    assert "matches" in data
    assert len(data["matches"]) > 0

    # Check structure of a match
    first_match = data["matches"][0]
    assert "id" in first_match
    assert "winner_next_match_id" in first_match

    # Ensure no old "nodes" key
    assert "nodes" not in data


async def test_update_settings(
    client: AsyncClient, auth_headers, valid_tournament_payload
):
    create_res = await client.post(
        "/tournaments", json=valid_tournament_payload, headers=auth_headers
    )
    t_id = create_res.json()["id"]

    update_payload = {"name": "Updated Name", "code": "9999"}
    response = await client.patch(
        f"/tournaments/{t_id}", json=update_payload, headers=auth_headers
    )

    assert response.status_code == 200
    data = response.json()
    assert data["name"] == "Updated Name"
