"""
认证路由 — 登录 / 登出 / 当前用户
"""

from fastapi import APIRouter, Depends, HTTPException, Request, status
from sqlmodel import Session, select

from app.core.deps import get_current_user
from app.core.security import verify_password
from app.db.session import get_session
from app.models.user import User
from app.schemas.auth import LoginRequest, UserResponse

router = APIRouter(prefix="/api/auth", tags=["认证"])


@router.post("/login", response_model=UserResponse)
def login(body: LoginRequest, request: Request, session: Session = Depends(get_session)):
    """账号登录。验证成功后写入 session，返回用户信息。"""
    statement = select(User).where(User.username == body.username)
    user = session.exec(statement).first()
    if user is None or not user.is_active:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
        )
    if not verify_password(body.password, user.password_hash):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
        )
    request.session["user_id"] = user.id
    return user


@router.post("/logout")
def logout(request: Request):
    """退出登录，清空当前 session。"""
    request.session.clear()
    return {"message": "已退出登录"}


@router.get("/me", response_model=UserResponse)
def get_me(user: User = Depends(get_current_user)):
    """获取当前登录用户的信息。"""
    return user