from functools import wraps
from flask import request, jsonify
import jwt
from ..services.config import Config
from ..services.mysql_service import get_db_connection

def role_required(*required_roles):
    """
    A decorator to ensure a user has one of the required roles.
    The user's role is expected to be in the JWT payload.
    """
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            token = None
            if 'x-access-token' in request.headers:
                token = request.headers['x-access-token']

            if not token:
                return jsonify({'message': 'Authentication token is missing!'}), 401

            try:
                data = jwt.decode(token, Config.JWT_SECRET_KEY, algorithms=["HS256"])
                user_role = data.get('role')
                current_user_pid = data.get('user') # Assuming 'user' key holds the pid

                if not user_role:
                    return jsonify({'message': 'Role information is missing from token!'}), 403

                if user_role not in required_roles:
                    return jsonify({'message': f'Access denied: Requires one of the following roles: {", ".join(required_roles)}'}), 403

            except jwt.ExpiredSignatureError:
                return jsonify({'message': 'Token has expired!'}), 401
            except jwt.InvalidTokenError:
                return jsonify({'message': 'Token is invalid!'}), 401

            # Pass the pid to the decorated function
            return f(current_user_pid, *args, **kwargs)
        return decorated_function
    return decorator
