from typing import Any, List

from fastapi import APIRouter, Body, Depends, Query, Path, status
from sqlalchemy.orm import Session

from app.api.deps import get_db, get_current_user, get_current_admin, get_current_super_admin
from app.crud.user import user
from app.models.user import User
from app.schemas.user import (
    UserResponse, UserUpdate, UserListResponse, 
    PaginationResponse, UserStatistics, BatchUserStatusUpdate
)
from app.utils.response import success_response
from app.utils.errors import NotFoundError, BadRequestError

router = APIRouter()


@router.get("/profile", response_model=UserResponse)
def get_user_profile(
    current_user: User = Depends(get_current_user),
) -> Any:
    """
    获取当前用户个人信息
    """
    return success_response(data=current_user)


@router.put("/profile", response_model=UserResponse)
def update_user_profile(
    *,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    user_in: UserUpdate,
) -> Any:
    """
    更新当前用户个人信息
    """
    # 更新用户信息
    db_user = user.update(db, db_obj=current_user, obj_in=user_in)
    
    return success_response(
        data=db_user,
        message="个人信息更新成功"
    )


@router.get("", response_model=UserListResponse)
def get_users(
    db: Session = Depends(get_db),
    current_admin: User = Depends(get_current_admin),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    user_type: str = Query(None, description="用户类型"),
    status: str = Query(None, description="用户状态"),
    keyword: str = Query(None, description="搜索关键词"),
) -> Any:
    """
    获取用户列表（管理员）
    """
    # 计算分页参数
    skip = (page - 1) * page_size
    
    # 获取用户列表
    users_list = user.get_multi(
        db, skip=skip, limit=page_size,
        user_type=user_type, status=status, keyword=keyword
    )
    
    # 获取用户总数
    total = user.count(
        db, user_type=user_type, status=status, keyword=keyword
    )
    
    # 计算总页数
    total_pages = (total + page_size - 1) // page_size
    
    # 构建分页信息
    pagination = PaginationResponse(
        page=page,
        page_size=page_size,
        total=total,
        total_pages=total_pages
    )
    
    return success_response(
        data={
            "users": users_list,
            "pagination": pagination
        }
    )


@router.get("/{user_id}", response_model=UserResponse)
def get_user_by_id(
    user_id: int = Path(..., ge=1),
    db: Session = Depends(get_db),
    current_admin: User = Depends(get_current_admin),
) -> Any:
    """
    获取用户详情（管理员）
    """
    # 获取用户
    db_user = user.get(db, user_id=user_id)
    if not db_user:
        raise NotFoundError("用户不存在")
    
    return success_response(data=db_user)


@router.get("/statistics", response_model=UserStatistics)
def get_user_statistics(
    db: Session = Depends(get_db),
    current_admin: User = Depends(get_current_admin),
) -> Any:
    """
    获取用户统计信息（管理员）
    """
    # 获取统计信息
    statistics = user.get_statistics(db)
    
    return success_response(data=statistics)


@router.post("/batch-status", response_model=dict)
def batch_update_user_status(
    *,
    db: Session = Depends(get_db),
    current_admin: User = Depends(get_current_admin),
    batch_in: BatchUserStatusUpdate,
) -> Any:
    """
    批量操作用户状态（管理员）
    """
    # 检查用户ID列表是否为空
    if not batch_in.user_ids:
        raise BadRequestError("用户ID列表不能为空")
    
    # 批量更新用户状态
    affected_rows = user.batch_update_status(
        db, user_ids=batch_in.user_ids, status=batch_in.status
    )
    
    return success_response(
        data={
            "message": f"成功更新{affected_rows}个用户的状态",
            "affected_rows": affected_rows
        }
    )


@router.delete("/{user_id}", response_model=dict)
def delete_user(
    user_id: int = Path(..., ge=1),
    db: Session = Depends(get_db),
    current_admin: User = Depends(get_current_super_admin),
) -> Any:
    """
    删除用户（超级管理员）
    """
    # 获取用户
    db_user = user.get(db, user_id=user_id)
    if not db_user:
        raise NotFoundError("用户不存在")
    
    # 删除用户
    user.remove(db, user_id=user_id)
    
    return success_response(
        data={
            "message": "用户删除成功",
            "user_id": user_id
        }
    )