from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func, or_
from config.database import get_db
from src.models.user import User
from src.schemas.user import (
    UserCreate,
    UserUpdate,
    UserResponse,
    UserListResponse,
    PasswordReset,
)
from src.utils.password import hash_password
from src.middleware.auth import require_admin
from typing import Optional

router = APIRouter(prefix="/users", tags=["用户管理"])


@router.get("", response_model=dict)
async def get_users(
    page: int = Query(1, ge=1),
    page_size: int = Query(10, ge=1, le=100),
    department: Optional[str] = None,
    role: Optional[str] = None,
    keyword: Optional[str] = None,
    current_user: User = Depends(require_admin),
    db: AsyncSession = Depends(get_db),
):
    query = select(User)

    if department:
        query = query.where(User.department == department)
    if role:
        query = query.where(User.role == role)
    if keyword:
        query = query.where(
            or_(
                User.username.contains(keyword),
                User.real_name.contains(keyword),
                User.email.contains(keyword),
            )
        )

    total_query = select(func.count()).select_from(query.subquery())
    total_result = await db.execute(total_query)
    total = total_result.scalar()

    query = query.offset((page - 1) * page_size).limit(page_size)
    result = await db.execute(query)
    users = result.scalars().all()

    return {
        "success": True,
        "message": "获取成功",
        "data": {
            "items": [UserResponse.model_validate(u) for u in users],
            "total": total,
            "page": page,
            "page_size": page_size,
        },
        "error_code": None,
    }


@router.post("", response_model=dict)
async def create_user(
    user_data: UserCreate,
    current_user: User = Depends(require_admin),
    db: AsyncSession = Depends(get_db),
):
    result = await db.execute(
        select(User).where(User.username == user_data.username)
    )
    if result.scalar_one_or_none():
        return {
            "success": False,
            "message": "用户名已存在",
            "data": None,
            "error_code": "2002",
        }

    if user_data.email:
        result = await db.execute(
            select(User).where(User.email == user_data.email)
        )
        if result.scalar_one_or_none():
            return {
                "success": False,
                "message": "邮箱已存在",
                "data": None,
                "error_code": "2002",
            }

    user = User(
        username=user_data.username,
        password_hash=hash_password(user_data.password),
        real_name=user_data.real_name,
        department=user_data.department,
        role=user_data.role,
        email=user_data.email,
        phone=user_data.phone,
    )
    db.add(user)
    await db.commit()
    await db.refresh(user)

    return {
        "success": True,
        "message": "用户创建成功",
        "data": UserResponse.model_validate(user),
        "error_code": None,
    }


@router.get("/{user_id}", response_model=dict)
async def get_user(
    user_id: int,
    current_user: User = Depends(require_admin),
    db: AsyncSession = Depends(get_db),
):
    result = await db.execute(select(User).where(User.id == user_id))
    user = result.scalar_one_or_none()

    if not user:
        return {
            "success": False,
            "message": "用户不存在",
            "data": None,
            "error_code": "2001",
        }

    return {
        "success": True,
        "message": "获取成功",
        "data": UserResponse.model_validate(user),
        "error_code": None,
    }


@router.put("/{user_id}", response_model=dict)
async def update_user(
    user_id: int,
    user_data: UserUpdate,
    current_user: User = Depends(require_admin),
    db: AsyncSession = Depends(get_db),
):
    result = await db.execute(select(User).where(User.id == user_id))
    user = result.scalar_one_or_none()

    if not user:
        return {
            "success": False,
            "message": "用户不存在",
            "data": None,
            "error_code": "2001",
        }

    update_data = user_data.model_dump(exclude_unset=True)
    for field, value in update_data.items():
        setattr(user, field, value)

    await db.commit()
    await db.refresh(user)

    return {
        "success": True,
        "message": "用户更新成功",
        "data": UserResponse.model_validate(user),
        "error_code": None,
    }


@router.delete("/{user_id}", response_model=dict)
async def delete_user(
    user_id: int,
    current_user: User = Depends(require_admin),
    db: AsyncSession = Depends(get_db),
):
    result = await db.execute(select(User).where(User.id == user_id))
    user = result.scalar_one_or_none()

    if not user:
        return {
            "success": False,
            "message": "用户不存在",
            "data": None,
            "error_code": "2001",
        }

    await db.delete(user)
    await db.commit()

    return {
        "success": True,
        "message": "用户删除成功",
        "data": None,
        "error_code": None,
    }


@router.post("/{user_id}/reset-password", response_model=dict)
async def reset_password(
    user_id: int,
    password_data: PasswordReset,
    current_user: User = Depends(require_admin),
    db: AsyncSession = Depends(get_db),
):
    result = await db.execute(select(User).where(User.id == user_id))
    user = result.scalar_one_or_none()

    if not user:
        return {
            "success": False,
            "message": "用户不存在",
            "data": None,
            "error_code": "2001",
        }

    user.password_hash = hash_password(password_data.new_password)
    await db.commit()

    return {
        "success": True,
        "message": "密码重置成功",
        "data": None,
        "error_code": None,
    }
