from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from config.database import get_db
from src.models.user import User
from src.schemas.auth import LoginRequest, LoginResponse
from src.schemas.user import UserResponse
from src.utils.password import verify_password
from src.utils.jwt import create_access_token
from src.middleware.auth import get_current_user

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


@router.post("/login", response_model=dict)
async def login(
    login_data: LoginRequest,
    db: AsyncSession = Depends(get_db),
):
    result = await db.execute(
        select(User).where(User.username == login_data.username)
    )
    user = result.scalar_one_or_none()

    if not user or not verify_password(login_data.password, user.password_hash):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail={
                "success": False,
                "message": "用户名或密码错误",
                "data": None,
                "error_code": "1002",
            }
        )

    if not user.is_active:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail={
                "success": False,
                "message": "用户未激活",
                "data": None,
                "error_code": "1002",
            }
        )

    access_token = create_access_token(
        data={"sub": str(user.id), "username": user.username}
    )

    return {
        "success": True,
        "message": "登录成功",
        "data": {
            "token": access_token,
            "token_type": "bearer",
            "user": UserResponse.model_validate(user),
        },
        "error_code": None,
    }


@router.get("/me", response_model=dict)
async def get_current_user_info(
    current_user: User = Depends(get_current_user),
):
    return {
        "success": True,
        "message": "获取成功",
        "data": UserResponse.model_validate(current_user),
        "error_code": None,
    }


@router.post("/logout", response_model=dict)
async def logout(current_user: User = Depends(get_current_user)):
    return {
        "success": True,
        "message": "登出成功",
        "data": None,
        "error_code": None,
    }
