from functools import wraps

from flask import abort, flash, redirect, request, url_for, jsonify
from flask_login import current_user


def require_role(*roles: str):
    """Restrict a route to users with one of the given roles.

    API endpoints (path starts /api/ or JSON request) receive a 403 JSON response.
    HTML endpoints get a flash message and redirect to inbox.
    Always stack below @login_required so current_user is populated.
    """
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            if not current_user.is_authenticated:
                return redirect(url_for('login'))
            if current_user.role not in roles:
                if request.is_json or request.path.startswith('/api/'):
                    return jsonify({'error': 'Forbidden'}), 403
                flash("You don't have permission to access that page.", "error")
                return redirect(url_for('inbox'))
            return f(*args, **kwargs)
        return wrapper
    return decorator
