from fastapi import APIRouter, Depends, Request
from ...core.database import get_db
from ...core.permission import require_login
from ...utils.request_utils import safe_json

router = APIRouter()


@router.post("/favorites")
async def add_favorite(
    request: Request,
    user: dict = Depends(require_login),
    db=Depends(get_db),
):
    """收藏知识库内容"""
    conn, cur = db
    body = await safe_json(request)
    point_id = body.get("point_id")
    collection = body.get("collection", "market_regulation_laws")
    title = body.get("title", "")

    if not point_id:
        return {"success": False, "error": "缺少 point_id"}

    user_id = user.get("userId", "1")

    try:
        await cur.execute(
            """INSERT INTO user_favorites (user_id, point_id, collection, title, created_at)
               VALUES (%s, %s, %s, %s, NOW())
               ON DUPLICATE KEY UPDATE title = VALUES(title), created_at = NOW()""",
            (user_id, point_id, collection, title),
        )
        favorite_id = cur.lastrowid
        return {
            "success": True,
            "message": "收藏成功",
            "data": {"id": favorite_id, "point_id": point_id, "collection": collection},
        }
    except Exception as e:
        return {"success": False, "error": f"收藏失败: {str(e)}"}


@router.get("/favorites")
async def list_favorites(
    request: Request,
    user: dict = Depends(require_login),
    db=Depends(get_db),
):
    """获取用户收藏列表"""
    user_id = user.get("userId", "1")
    conn, cur = db

    try:
        await cur.execute(
            """SELECT id, point_id, collection, title, created_at
               FROM user_favorites
               WHERE user_id = %s
               ORDER BY created_at DESC""",
            (user_id,),
        )
        rows = await cur.fetchall()

        favorites = []
        for row in rows:
            favorites.append({
                "id": row["id"],
                "point_id": row["point_id"],
                "collection": row["collection"],
                "title": row["title"],
                "created_at": str(row["created_at"]) if row["created_at"] else None,
            })

        return {"success": True, "data": favorites}
    except Exception as e:
        return {"success": False, "error": f"获取收藏列表失败: {str(e)}"}


@router.delete("/favorites/{favorite_id}")
async def remove_favorite(
    favorite_id: int,
    request: Request,
    user: dict = Depends(require_login),
    db=Depends(get_db),
):
    """取消收藏"""
    user_id = user.get("userId", "1")
    conn, cur = db

    try:
        await cur.execute(
            "DELETE FROM user_favorites WHERE id = %s AND user_id = %s",
            (favorite_id, user_id),
        )
        return {"success": True, "message": "取消收藏成功"}
    except Exception as e:
        return {"success": False, "error": f"取消收藏失败: {str(e)}"}


@router.get("/favorites/check")
async def check_favorite(
    request: Request,
    user: dict = Depends(require_login),
    db=Depends(get_db),
):
    """检查是否已收藏"""
    user_id = user.get("userId", "1")
    conn, cur = db

    from fastapi import Query
    point_id = request.query_params.get("point_id", "")
    collection = request.query_params.get("collection", "market_regulation_laws")

    if not point_id:
        return {"success": False, "error": "缺少 point_id"}

    try:
        await cur.execute(
            "SELECT id FROM user_favorites WHERE user_id = %s AND point_id = %s AND collection = %s",
            (user_id, point_id, collection),
        )
        row = await cur.fetchone()
        return {
            "success": True,
            "data": {"is_favorited": row is not None, "favorite_id": row["id"] if row else None},
        }
    except Exception as e:
        return {"success": False, "error": f"检查收藏状态失败: {str(e)}"}
