from functools import wraps

from flask import jsonify
from flask_jwt_extended import get_jwt, get_jwt_identity, verify_jwt_in_request

from app.models import User


def current_user() -> User | None:
    identity = get_jwt_identity()
    if not identity:
        return None
    return User.query.get(int(identity))


def admin_required(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        verify_jwt_in_request()
        claims = get_jwt()
        if not claims.get("is_admin", False):
            return jsonify({"code": 403, "message": "需要管理员权限"}), 403
        return fn(*args, **kwargs)

    return wrapper
