from functools import wraps
from flask_jwt_extended import verify_jwt_in_request, get_jwt_identity
from app.models.user import User
from app.services.settings_service import is_allowed


def role_required(*roles):
    def decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            verify_jwt_in_request()
            user_id = get_jwt_identity()
            user = User.query.get(user_id)
            if not user or user.access_level not in roles:
                return {"success": False, "message": "Forbidden"}, 403
            return fn(*args, **kwargs)
        return wrapper
    return decorator


def permission_required(permission_key: str):
    def decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            verify_jwt_in_request()
            user_id = get_jwt_identity()
            user = User.query.get(user_id)
            if not user:
                return {"success": False, "message": "Unauthorized"}, 401
            if not is_allowed(user.access_level, permission_key):
                return {"success": False, "message": "Forbidden"}, 403
            return fn(*args, **kwargs)

        return wrapper

    return decorator
