"""Интеграционные тесты `/api/v1/teams`: справочник команд для
выбора в профиле — доступен любому аутентифицированному пользователю (не гейтится
`registration_team_choice`, в отличие от `/auth/registration-options`; не требует
роли admin, в отличие от `/admin/teams`).
"""

import uuid

import httpx
from sqlalchemy.ext.asyncio import AsyncSession

from core.security import create_access_token, hash_password
from models.team import Team
from models.user import User


async def _make_user(session: AsyncSession) -> User:
    user = User(
        email=f"{uuid.uuid4()}@example.com",
        name_user="Teams API Tester",
        password_hash=await hash_password("password123"),
        email_verified=True,
    )
    session.add(user)
    await session.flush()
    return user


async def _make_team(session: AsyncSession) -> Team:
    team = Team(name=f"Team {uuid.uuid4()}")
    session.add(team)
    await session.flush()
    return team


def _auth_headers(user: User) -> dict[str, str]:
    token = create_access_token(user.id, user.role)
    return {"Authorization": f"Bearer {token}"}


async def test_regular_user_gets_full_team_list(
    client: httpx.AsyncClient, db_session: AsyncSession
) -> None:
    user = await _make_user(db_session)
    team = await _make_team(db_session)
    await db_session.commit()

    response = await client.get("/api/v1/teams", headers=_auth_headers(user))
    assert response.status_code == 200, response.text
    item = next(i for i in response.json() if i["id"] == str(team.id))
    assert item["name"] == team.name


async def test_list_teams_requires_authentication(client: httpx.AsyncClient) -> None:
    response = await client.get("/api/v1/teams")
    assert response.status_code == 401
