from fastapi import APIRouter, Depends, Query, Request
from ...core.database import get_db
from ...core.permission import get_current_user, is_admin_role

router = APIRouter()


@router.get("")
async def list_threads(
    request: Request,
    page: int = Query(1, ge=1),
    pageSize: int = Query(20, ge=1, le=100),
    keyword: str = Query(""),
    db=Depends(get_db),
):
    current_user = get_current_user(request)
    if not current_user or not is_admin_role(current_user["role"]):
        return {"error": "无权限", "detail": "admin required"}

    conn, cur = db
    try:
        where = ""
        params = []
        if keyword:
            where = "WHERE t.thread_id LIKE %s OR u.username LIKE %s"
            params.extend([f"%{keyword}%", f"%{keyword}%"])

        await cur.execute(f"SELECT COUNT(*) as total FROM threads t LEFT JOIN users u ON t.user_id = u.id {where}", params)
        total = dict(await cur.fetchone())["total"]

        offset = (page - 1) * pageSize
        await cur.execute(
            f"""SELECT t.id, t.thread_id, t.title, t.message_count, t.created_at, t.user_id, u.username
             FROM threads t LEFT JOIN users u ON t.user_id = u.id
             {where} ORDER BY t.created_at DESC LIMIT %s OFFSET %s""",
            params + [pageSize, offset],
        )
        rows = await cur.fetchall()
        return {"list": [dict(r) for r in rows], "total": total, "page": page, "pageSize": pageSize}
    except Exception:
        return {"list": [], "total": 0, "page": page, "pageSize": pageSize}
