from functools import wraps
from flask import redirect, url_for, flash, request
from flask_login import current_user


def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        print(f"DEBUG: login_required 检查 - current_user.is_authenticated = {current_user.is_authenticated}")
        if not current_user.is_authenticated:
            flash('请先登录', 'warning')
            return redirect(url_for('user.login', next=request.url))
        return f(*args, **kwargs)

    return decorated_function


def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        print(f"DEBUG: admin_required 检查 - current_user.is_authenticated = {current_user.is_authenticated}")
        if not current_user.is_authenticated:
            flash('请先登录', 'warning')
            return redirect(url_for('user.login', next=request.url))

        print(f"DEBUG: admin_required 检查 - current_user.role_id = {getattr(current_user, 'role_id', None)}")
        if getattr(current_user, 'role_id', None) != 1:  # 安全地获取role_id属性
            flash('权限不足', 'danger')
            return redirect(url_for('index'))
        return f(*args, **kwargs)

    return decorated_function


def permission_required(permission_code):
    """
    检查用户是否拥有特定权限的装饰器
    :param permission_code: 权限代码，例如 'manage_books'
    """

    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            print(
                f"DEBUG: permission_required({permission_code}) 检查 - current_user.is_authenticated = {current_user.is_authenticated}")

            # 检查用户是否登录
            if not current_user.is_authenticated:
                flash('请先登录', 'warning')
                return redirect(url_for('user.login', next=request.url))

            # 管理员拥有所有权限
            if getattr(current_user, 'role_id', None) == 1:
                return f(*args, **kwargs)

            # 获取用户角色并检查是否有指定权限
            from app.models.user import Role
            role = Role.query.get(current_user.role_id)

            if not role:
                flash('用户角色异常', 'danger')
                return redirect(url_for('index'))

            # 检查角色是否有指定权限
            has_permission = False
            for perm in role.permissions:
                if perm.code == permission_code:
                    has_permission = True
                    break

            if not has_permission:
                print(f"DEBUG: 用户 {current_user.username} 缺少权限 {permission_code}")
                flash('您没有执行此操作的权限', 'danger')
                return redirect(url_for('index'))

            return f(*args, **kwargs)

        return decorated_function

    return decorator

