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

from core.security import get_current_admin_user
from app.database import get_db
from app.models import User

router = APIRouter()

@router.get("/users", response_model=List[dict])
async def get_users(
    current_user: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """获取用户列表（管理员功能）"""
    
    users = db.query(User).all()
    result = []
    for user in users:
        result.append({
            "id": user.id,
            "username": user.username,
            "role": user.role,
            "created_at": user.created_at.isoformat() if user.created_at else None
        })
    return result

@router.post("/users", response_model=dict)
async def create_user(
    username: str,
    password: str,
    role: str = "user",
    current_user: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """创建新用户（管理员功能）"""
    # 检查用户名是否已存在
    existing = db.query(User).filter(User.username == username).first()
    if existing:
        raise HTTPException(status_code=400, detail="用户名已存在")
    
    # 密码哈希
    hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
    
    user = User(
        username=username,
        password_hash=hashed_password,
        role=role or "user"
    )
    db.add(user)
    db.commit()
    db.refresh(user)
    return {"message": "创建成功", "user_id": user.id}

@router.put("/users/{user_id}", response_model=dict)
async def update_user(
    user_id: int,
    username: str = None,
    password: str = None,
    role: str = None,
    current_user: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """更新用户（管理员功能）"""
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    if username:
        existing = db.query(User).filter(User.username == username).first()
        if existing and existing.id != user_id:
            raise HTTPException(status_code=400, detail="用户名已存在")
        user.username = username
    
    if password:
        user.password_hash = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
    
    if role:
        user.role = role
    
    db.commit()
    db.refresh(user)
    return {"message": "更新成功"}

@router.delete("/users/{user_id}")
async def delete_user(
    user_id: int,
    current_user: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """删除用户（管理员功能）"""
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    if user.role == "admin":
        raise HTTPException(status_code=400, detail="不能删除管理员用户")
    
    db.delete(user)
    db.commit()
    return {"message": "删除成功"}
