# -*- coding: utf-8 -*-
"""
认证端点
处理用户登录，签发 JWT 令牌。
"""

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

from app.core.database import get_db
from app.core.security import create_access_token
from app.crud.user import authenticate_user
from app.schemas.user import Token, UserLogin

router = APIRouter()


@router.post("/login", response_model=Token, summary="用户登录", tags=["认证"])
async def login(body: UserLogin, db: AsyncSession = Depends(get_db)):
    """
    校验用户名密码，成功后签发 JWT access_token。
    前端后续请求需在 Authorization 头携带 Bearer <token>。
    """
    user = await authenticate_user(db, body.username, body.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )

    token = create_access_token(subject=user.username, role=user.role)
    return Token(
        access_token=token,
        role=user.role,
        username=user.username,
    )
