from __future__ import annotations

from fastapi import APIRouter, Depends, Query
from sqlalchemy import select
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.core.dependencies import get_current_admin
from app.core.responses import api_success
from app.models.admin import Admin
from app.models.user import User
from app.schemas.admin import AdminUserUpdateRequest
from app.services.admin_service import OperationLogService

router = APIRouter()


@router.get("/user/list")
def list_users(
    keyword: str = Query(default=""),
    db: Session = Depends(get_db),
    current_admin: Admin = Depends(get_current_admin),
) -> dict:
    query = select(User).where(User.is_deleted == 0).order_by(User.id.desc())
    if keyword:
        like = f"%{keyword}%"
        query = query.where((User.phone.like(like)) | (User.name.like(like)))
    users = db.scalars(query.limit(200)).all()
    return api_success([_user_dict(user) for user in users])


@router.get("/user/{user_id}")
def user_detail(
    user_id: int,
    db: Session = Depends(get_db),
    current_admin: Admin = Depends(get_current_admin),
) -> dict:
    user = _get_user(db, user_id)
    return api_success(_user_dict(user))


@router.put("/user/{user_id}")
def update_user(
    user_id: int,
    payload: AdminUserUpdateRequest,
    db: Session = Depends(get_db),
    current_admin: Admin = Depends(get_current_admin),
) -> dict:
    user = _get_user(db, user_id)
    if payload.status is not None:
        user.status = payload.status
    if payload.dailyChatLimit is not None:
        user.daily_chat_limit = payload.dailyChatLimit
    if payload.expiredAt is not None:
        user.expired_at = payload.expiredAt.replace(tzinfo=None)
    db.add(user)
    OperationLogService.write(db, admin_id=current_admin.id, module="user", action="update", target_id=user.id)
    db.commit()
    db.refresh(user)
    return api_success(_user_dict(user))


@router.delete("/user/{user_id}")
def delete_user(
    user_id: int,
    db: Session = Depends(get_db),
    current_admin: Admin = Depends(get_current_admin),
) -> dict:
    user = _get_user(db, user_id)
    user.is_deleted = 1
    db.add(user)
    OperationLogService.write(db, admin_id=current_admin.id, module="user", action="delete", target_id=user.id)
    db.commit()
    return api_success()


def _get_user(db: Session, user_id: int) -> User:
    user = db.get(User, user_id)
    if user is None or user.is_deleted:
        from fastapi import HTTPException, status

        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
    return user


def _user_dict(user: User) -> dict:
    return {
        "id": user.id,
        "phone": user.phone,
        "name": user.name,
        "nickname": user.nickname,
        "status": user.status,
        "dailyChatLimit": user.daily_chat_limit,
        "dailyChatUsed": user.daily_chat_used,
        "expiredAt": user.expired_at,
        "lastLoginAt": user.last_login_at,
        "createdAt": user.created_at,
    }
