"""
Overstyring av HCP for en KONTOKOBLET medspiller ved selve opprettelsen
(2026-08-20, brukerfunn: "Ny runde"-veiviseren kunne ikke overstyre HCP
for en nylig lagt til medspiller fra første stund -- kun i etterkant via
PATCH .../participants/{id}, som allerede støttet det, jf. ADR-038: "HCP
... brukes til Course Handicap i enhver runde med mindre eksplisitt
overstyrt"). Kaller add_participant direkte, samme mønster som
test_flag_plant.py.
"""

import uuid

from app.auth import CurrentUser
from app.routers.rounds import ParticipantCreate, add_participant

from tests.conftest import create_user

import app.db as app_db


async def _setup_round_with_custom_course(owner_user_id: str) -> str:
    """course_source='custom' (DB-only banedata, ingen nettverkskall mot
    teeoff, ulikt 'teeoff'-fixturen conftest.create_round bruker) -- add_
    participant slår alltid opp banens rating når handicap_index er satt."""
    async with app_db.plain_connection() as conn:
        personal_course_id = str(uuid.uuid4())
        await conn.execute(
            "INSERT INTO personal_course (id, created_by_user_id, name) VALUES ($1, $2, 'Hjemmebanen')",
            personal_course_id, owner_user_id,
        )
        for n in range(1, 19):
            await conn.execute(
                "INSERT INTO personal_course_hole (personal_course_id, hole_number, par, stroke_index) "
                "VALUES ($1, $2, 4, $3)",
                personal_course_id, n, n,
            )
        tee_id = str(uuid.uuid4())
        await conn.execute(
            "INSERT INTO personal_course_tee (id, personal_course_id, name) VALUES ($1, $2, 'Gul')",
            tee_id, personal_course_id,
        )
        for gender in ("m", "f"):
            await conn.execute(
                "INSERT INTO personal_course_tee_rating "
                "(personal_course_tee_id, gender, course_rating, slope_rating, par) "
                "VALUES ($1, $2, 71.5, 125, 72)",
                tee_id, gender,
            )
        round_id = str(uuid.uuid4())
        await conn.execute(
            """
            INSERT INTO round (id, owner_user_id, course_source, personal_course_id,
                                course_name_snapshot, tee_name_snapshot, played_at)
            VALUES ($1, $2, 'custom', $3, 'Hjemmebanen', 'Gul', CURRENT_DATE)
            """,
            round_id, owner_user_id, personal_course_id,
        )
    return round_id


async def test_add_participant_honors_explicit_handicap_override_for_linked_account(pool):
    owner_id = await create_user()
    target_id = await create_user(display_name="Medspiller")
    async with app_db.plain_connection() as conn:
        await conn.execute("UPDATE app_user SET gender = 'm', handicap_index = 18.4 WHERE id = $1", target_id)
    round_id = await _setup_round_with_custom_course(owner_id)

    user = CurrentUser(user_id=owner_id)
    result = await add_participant(
        round_id,
        ParticipantCreate(user_id=target_id, handicap_index=9.1),
        user=user,
    )
    assert result.handicap_index_snapshot == 9.1
    assert result.course_handicap_snapshot is not None


async def test_add_participant_falls_back_to_profile_handicap_when_no_override_given(pool):
    """Regresjonsvern -- uendret oppførsel når organisatoren IKKE oppgir
    noen overstyring (feltet stått urørt i veiviseren)."""
    owner_id = await create_user()
    target_id = await create_user(display_name="Medspiller")
    async with app_db.plain_connection() as conn:
        await conn.execute("UPDATE app_user SET gender = 'm', handicap_index = 18.4 WHERE id = $1", target_id)
    round_id = await _setup_round_with_custom_course(owner_id)

    user = CurrentUser(user_id=owner_id)
    result = await add_participant(
        round_id,
        ParticipantCreate(user_id=target_id),
        user=user,
    )
    assert result.handicap_index_snapshot == 18.4
