"""
Shotgun-start for Cup-/lagformatet (migrasjon 088, ADR-096) -- samme
mønster som individuelle turneringers utslagsgrupper
(test_round_groups.py), men for session/match. Bruker: "Det må komme
frem om det er Shotgun eller løpende start... Sorteringen av
startlisten gjøres etter utslagsform."
"""

from app.routers.matches import MatchCreate, create_match, list_matches
from app.routers.tournaments import SessionUpdate, update_session
from app.auth import CurrentUser

import app.db as app_db

from tests.conftest import (
    add_membership,
    create_course,
    create_org,
    create_session,
    create_team,
    create_tournament,
    create_user,
)


async def _setup(org_id):
    owner_id = await create_user()
    await add_membership(org_id, owner_id, role="owner")
    tournament_id = await create_tournament(org_id, name="Cup-turnering")
    course_id = await create_course(org_id, name="Cup Links")
    session_id = await create_session(org_id, tournament_id, course_id, format="foursome")
    team_a = await create_team(org_id, tournament_id, name="Team Nord")
    team_b = await create_team(org_id, tournament_id, name="Team Sør")
    return owner_id, tournament_id, session_id, team_a, team_b


async def test_shotgun_session_gives_all_matches_the_same_tee_time(pool):
    org_id = await create_org()
    owner_id, tournament_id, session_id, team_a, team_b = await _setup(org_id)

    await update_session(
        session_id,
        SessionUpdate(scheduled_at="2026-08-19T08:00:00", tee_interval_minutes=10, start_mode="shotgun"),
        organization_id=org_id,
    )

    m1 = (await create_match(
        session_id, MatchCreate(sequence=1, team_a_id=team_a, team_b_id=team_b, start_hole=5),
        organization_id=org_id,
    )).id
    m2 = (await create_match(
        session_id, MatchCreate(sequence=2, team_a_id=team_a, team_b_id=team_b, start_hole=1),
        organization_id=org_id,
    )).id

    user = CurrentUser(user_id=owner_id)
    matches = await list_matches(session_id, organization_id=org_id, user=user)
    # Begge matcher går ut kl 08:00, uansett sequence/intervall.
    for m in matches:
        assert m.tee_time is not None and m.tee_time.isoformat().startswith("2026-08-19T08:00:00")
    # Vist sortert etter STARTHULL (1 før 5), ikke sequence (m1 før m2).
    assert [m.start_hole for m in matches] == [1, 5]
    assert [m.id for m in matches] == [m2, m1]


async def test_consecutive_session_still_sorts_by_sequence(pool):
    org_id = await create_org()
    owner_id, tournament_id, session_id, team_a, team_b = await _setup(org_id)

    await update_session(
        session_id,
        SessionUpdate(scheduled_at="2026-08-19T08:00:00", tee_interval_minutes=10),
        organization_id=org_id,
    )

    m1 = (await create_match(
        session_id, MatchCreate(sequence=1, team_a_id=team_a, team_b_id=team_b),
        organization_id=org_id,
    )).id
    m2 = (await create_match(
        session_id, MatchCreate(sequence=2, team_a_id=team_a, team_b_id=team_b),
        organization_id=org_id,
    )).id

    user = CurrentUser(user_id=owner_id)
    matches = await list_matches(session_id, organization_id=org_id, user=user)
    assert [m.id for m in matches] == [m1, m2]
    assert matches[0].tee_time.isoformat().startswith("2026-08-19T08:00:00")
    assert matches[1].tee_time.isoformat().startswith("2026-08-19T08:10:00")


async def test_match_tee_time_override_wins_even_in_shotgun_mode(pool):
    org_id = await create_org()
    owner_id, tournament_id, session_id, team_a, team_b = await _setup(org_id)

    await update_session(
        session_id,
        SessionUpdate(scheduled_at="2026-08-19T08:00:00", start_mode="shotgun"),
        organization_id=org_id,
    )
    match_id = (await create_match(
        session_id, MatchCreate(sequence=1, team_a_id=team_a, team_b_id=team_b, start_hole=9),
        organization_id=org_id,
    )).id
    async with app_db.org_connection(org_id) as conn:
        await conn.execute(
            "UPDATE match SET tee_time_override = '2026-08-19T09:30:00' WHERE id = $1", match_id
        )

    user = CurrentUser(user_id=owner_id)
    matches = await list_matches(session_id, organization_id=org_id, user=user)
    assert matches[0].tee_time.isoformat().startswith("2026-08-19T09:30:00")
