from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app.core.security import create_access_token, verify_password
from app.db.session import get_db
from app.models import AdminUser
from app.schemas.auth import LoginRequest, LoginResponse

router = APIRouter()


@router.post("/login", response_model=LoginResponse)
def login(payload: LoginRequest, db: Session = Depends(get_db)) -> LoginResponse:
    admin = db.query(AdminUser).filter(AdminUser.username == payload.username).first()
    if not admin or admin.status != "active" or not verify_password(payload.password, admin.password_hash):
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="账号或密码错误，请重试")
    return LoginResponse(
        access_token=create_access_token(str(admin.id), admin.role_code),
        role_code=admin.role_code,
        username=admin.username,
    )
