"""
团队相关 API 路由
"""

from typing import List, Optional

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import or_, select
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.deps import get_current_active_user as get_current_user, get_db
from app.core.logger import logger
from app.models.user import Team
from app.schemas.base import ResponseModel


router = APIRouter(prefix="/teams", tags=["teams"])


@router.get("/", response_model=ResponseModel)
async def list_teams(
    keyword: Optional[str] = Query(None, description="按名称或编码模糊搜索"),
    current_user=Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
) -> ResponseModel:
    """
    获取团队列表

    任何登录用户均可查询团队列表，用于前端下拉选择。
    """
    try:
        stmt = select(Team).where(Team.is_deleted == False)  # noqa: E712
        if keyword:
            like = f"%{keyword}%"
            stmt = stmt.where(or_(Team.name.ilike(like), Team.code.ilike(like)))

        rows: List[Team] = (await db.execute(stmt)).scalars().all()
        data = [
            {
                "id": t.id,
                "name": t.name,
                "code": t.code,
                "team_type": t.team_type,
            }
            for t in rows
        ]
        return ResponseModel(code=200, message="OK", data=data)
    except Exception:
        logger.error("查询团队列表失败", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="查询团队列表失败",
        )


