import uuid

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

from app.api.base import PaginationParams
from app.api.deps import get_current_user
from app.database import get_db
from app.models.user import User
from app.services.admin import (
    get_system_stats,
    get_user_detail,
    get_users,
    toggle_user_active,
    update_user_plan,
)

router = APIRouter(prefix="/api/v1/admin", tags=["admin"])


async def get_admin_user(current_user: User = Depends(get_current_user)) -> User:
    if not current_user.is_admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="需要管理员权限",
        )
    return current_user


@router.get("/stats")
async def read_system_stats(
    db: AsyncSession = Depends(get_db),
    admin_user: User = Depends(get_admin_user),
):
    return await get_system_stats(db)


@router.get("/users")
async def read_users(
    pagination: PaginationParams = Depends(PaginationParams),
    search: str | None = Query(None),
    db: AsyncSession = Depends(get_db),
    admin_user: User = Depends(get_admin_user),
):
    return await get_users(db, skip=pagination.offset, limit=pagination.limit, search=search)


@router.get("/users/{user_id}")
async def read_user_detail(
    user_id: uuid.UUID,
    db: AsyncSession = Depends(get_db),
    admin_user: User = Depends(get_admin_user),
):
    detail = await get_user_detail(db, user_id)
    if detail is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在",
        )
    return detail


@router.post("/users/{user_id}/toggle-active")
async def toggle_user_active_status(
    user_id: uuid.UUID,
    db: AsyncSession = Depends(get_db),
    admin_user: User = Depends(get_admin_user),
):
    result = await toggle_user_active(db, user_id)
    if result is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在",
        )
    return result


class UpdatePlanRequest:
    plan: str


@router.put("/users/{user_id}/update-plan")
async def modify_user_plan(
    user_id: uuid.UUID,
    body: dict,
    db: AsyncSession = Depends(get_db),
    admin_user: User = Depends(get_admin_user),
):
    plan = body.get("plan")
    if not plan:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="缺少 plan 字段",
        )
    try:
        result = await update_user_plan(db, user_id, plan)
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e),
        )
    if result is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在",
        )
    return result
