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

from app.core.database import get_db
from app.core.security import decode_token, create_token_pair
from app.schemas.auth import LoginRequest, Token, TokenRefresh
from app.schemas.common import ResponseModel
from app.services.auth_service import login

router = APIRouter()


@router.post("/login", response_model=ResponseModel[Token])
def api_login(req: LoginRequest, db: Session = Depends(get_db)):
    token_data = login(db, req.username, req.password)
    return ResponseModel(data=Token(**token_data))


@router.post("/refresh", response_model=ResponseModel[Token])
def api_refresh(req: TokenRefresh):
    payload = decode_token(req.refresh_token)
    if not payload or payload.get("type") != "refresh":
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的刷新令牌",
        )
    user_id = int(payload.get("sub"))
    username = payload.get("username")
    access_token, refresh_token = create_token_pair(user_id, username)
    return ResponseModel(data=Token(
        access_token=access_token,
        refresh_token=refresh_token,
        token_type="bearer",
        expires_in=30 * 60,
    ))
