from fastapi import APIRouter, HTTPException, status
from ...core.auth import authenticate, generate_token
from ...schemas.auth import LoginRequest

router = APIRouter()


@router.post("/login")
async def admin_login(body: LoginRequest):
    if not body.username or not body.password:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户名和密码不能为空",
        )

    user_info = await authenticate(body.username, body.password)
    if not user_info:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
        )

    # Only admin role can access admin endpoints
    if user_info["role"] != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无管理员权限，请通过用户端登录",
        )

    token = generate_token(
        user_id=user_info["user_id"],
        username=user_info["username"],
        role=user_info["role"],
    )

    return {
        "token": token,
        "user": {
            "id": user_info["user_id"],
            "username": user_info["username"],
            "real_name": user_info.get("name"),
            "role": user_info["role"],
        },
        "menus": [],
    }
