"""
Retting av en spillers handicap-indeks DIREKTE i en turnering
(2026-08-18). Bruker: "Hvordan ... justerer hcp på spillere?" -- å
redigere spilleren i org-spillerpoolen (ADR-085) rører aldri en
allerede satt `tournament_participant.handicap_index_snapshot` (samme
"frosset snapshot"-filosofi som lagturneringers team_roster), så det
manglet en direkte vei til å rette EN SPESIFIKK deltakers indeks i
turneringen den faktisk gjelder for.
"""

from app.routers.individual_tournaments import (
    TournamentParticipantUpdate,
    update_tournament_participant,
)

from tests.conftest import (
    create_org,
    create_course,
    create_player,
    create_tee,
    create_tournament,
    create_tournament_participant,
    create_tournament_round,
    create_tournament_round_participant,
)

import app.db as app_db


async def test_update_handicap_snapshot(pool):
    org_id = await create_org()
    tournament_id = await create_tournament(org_id)
    player_id = await create_player(org_id, display_name="Spiller")
    tp_id = await create_tournament_participant(org_id, tournament_id, player_id)

    async with app_db.org_connection(org_id) as conn:
        await conn.execute(
            "UPDATE tournament_participant SET handicap_index_snapshot = 24.0 WHERE id = $1", tp_id
        )

    updated = await update_tournament_participant(
        tournament_id, tp_id, TournamentParticipantUpdate(handicap_index_snapshot=11.5), organization_id=org_id
    )
    assert updated.handicap_index_snapshot == 11.5


async def test_updating_snapshot_does_not_retroactively_change_already_frozen_round_handicap(pool):
    """Samme "frosset snapshot"-prinsipp som PlayerUpdate allerede
    dokumenterer for team_roster -- en rettelse i tournament_participant
    skal ALDRI skrive over et allerede satt tournament_round_participant.
    course_handicap/playing_handicap for en runde deltakeren allerede er
    satt opp i."""
    org_id = await create_org()
    tournament_id = await create_tournament(org_id)
    course_id = await create_course(org_id)
    tee_id = await create_tee(org_id, course_id)
    round_id = await create_tournament_round(org_id, tournament_id, course_id)
    player_id = await create_player(org_id, display_name="Spiller")
    tp_id = await create_tournament_participant(org_id, tournament_id, player_id)
    rp_id = await create_tournament_round_participant(org_id, round_id, tp_id, tee_id, course_handicap=10)

    await update_tournament_participant(
        tournament_id, tp_id, TournamentParticipantUpdate(handicap_index_snapshot=2.0), organization_id=org_id
    )

    async with app_db.org_connection(org_id) as conn:
        frozen = await conn.fetchval(
            "SELECT course_handicap FROM tournament_round_participant WHERE id = $1", rp_id
        )
    assert frozen == 10  # uendret, ikke omregnet fra den nye indeksen
