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

pytestmark = pytest.mark.anyio


async def test_scoring_flow(
    client: AsyncClient, auth_headers, valid_tournament_payload
):
    # 1. Create Tournament
    res = await client.post(
        "/tournaments", json=valid_tournament_payload, headers=auth_headers
    )
    t_id = res.json()["id"]
    t_code = valid_tournament_payload["code"]

    # 2. Get Bracket (Now returns list of Matches)
    # Note: You can now get this from GET /tournaments/{id} or /bracket depending on your routes
    bracket_res = await client.get(f"/tournaments/{t_id}")
    matches = bracket_res.json()["matches"]

    # Find the first playable match (Round 1)
    # We look for a match that has teams assigned but is not finished
    active_match = next(
        m
        for m in matches
        if m["status"] == "Pending" and m["p1_team_id"] and m["p2_team_id"]
    )

    match_id = active_match["id"]
    next_match_id = active_match["winner_next_match_id"]

    # 3. Report Score
    score_payload = {
        "id": match_id,
        "code": t_code,
        "sets": [{"p1": 21, "p2": 19}, {"p1": 21, "p2": 15}],
    }

    report_res = await client.post(
        f"/tournaments/{t_id}/matches/{match_id}/score", json=score_payload
    )
    assert report_res.status_code == 200

    # 4. Verify Winner Advanced
    updated_res = await client.get(f"/tournaments/{t_id}")
    updated_matches = updated_res.json()["matches"]

    target_match = next(m for m in updated_matches if m["id"] == next_match_id)

    winner_id = active_match["p1_team_id"]

    # Check if winner is now in the next match
    p1_in_target = target_match["p1_team_id"]
    p2_in_target = target_match["p2_team_id"]

    assert winner_id in [p1_in_target, p2_in_target]

    # 5. Test Invalid Code
    bad_payload = score_payload.copy()
    bad_payload["code"] = "WRONG"
    bad_res = await client.post(
        f"/tournaments/{t_id}/matches/{match_id}/score", json=bad_payload
    )
    assert bad_res.status_code == 403


async def test_clear_score(client: AsyncClient, auth_headers, valid_tournament_payload):
    # Setup
    res = await client.post(
        "/tournaments", json=valid_tournament_payload, headers=auth_headers
    )
    t_id = res.json()["id"]

    # Get active match
    detail = (await client.get(f"/tournaments/{t_id}")).json()
    active_match = next(
        m for m in detail["matches"] if m["p1_team_id"] and m["p2_team_id"]
    )
    match_id = active_match["id"]

    score_payload = {"id": match_id, "code": "1234", "sets": [{"p1": 25, "p2": 0}]}
    await client.post(
        f"/tournaments/{t_id}/matches/{match_id}/score", json=score_payload
    )

    # Verify Finished
    check_res = await client.get(f"/tournaments/{t_id}/matches/{match_id}")
    assert check_res.json()["status"] == "Finished"

    # Action: Clear Score
    clear_res = await client.delete(
        f"/tournaments/{t_id}/matches/{match_id}/score", headers=auth_headers
    )
    assert clear_res.status_code == 200

    # Verify Reset
    final_res = await client.get(f"/tournaments/{t_id}/matches/{match_id}")
    data = final_res.json()

    assert data["status"] == "Pending"
    assert data["winner_team_id"] is None
    assert len(data["sets"]) == 0
